Click here to Skip to main content
12,078,259 members (46,822 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C++
Hey

I have a class named Yup and it has one data member of type int(called number).
I have overloaded the cout and + operators.

cout<<object(type Yup)==> prints the number.
The object1+object2 adds the numbers of 2 objects.

In the main I have

Yup t(23),t1(27);

When I do this: Yup t2=t+t1; cout<<t2<<endl;==> I get 50;


When I do this: cout<<(t+t1)<<endl; ==> I get -87293...

How can i write it in one line?
How it is compiled?


ostream &operator<<( ostream &output, const Yup &num )
{
    output<<num.number;
    return output;
}
 
Yup &operator+(const Yup &tr1,const Yup &tr2 )
{
    Yup k(0);
    k.number=tr1.number+tr2.number;
    return k;
}
Posted 25-Nov-12 3:29am
Edited 25-Nov-12 4:50am
v3
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Your operator+ overload[^] returns a reference to a local variable.

Remove the reference:
Yup operator+( const Yup &tr1,const Yup &tr2 )
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

You probably have defined operator+ incorrectly. It should return an object of your class that contains the result. If in doubt, show your code by using the "Improve question" button on your question.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web04 | 2.8.160212.1 | Last Updated 25 Nov 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100