Re: initial value of reference to non-const must be an lvalue
On Jan 11, 10:43 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
asm23 wrote:
Hi,I need some help to clarify the warning "initial value of reference
to non-const must be an lvalue".
I'm searching in this groups to find someone has the same situation
like me. I found in the Post:
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/e81...
//*********************************************************************
// CODE
//*********************************************************************
#include <iostream.h>
class ostream; =
//Need for Overloading <<
class complex {
double re, im; =
//Private members of class
public:
complex() { re=0.0; im=0.0; } //Empty Co=
nstructor
complex(double r, double i=0.0) //Constructor =
from 2
doubles { re=r; im=i; }
friend ostream& operator<<(ostream&, complex&);
friend inline complex operator+(complex, complex);
};
inline complex operator+(complex a1, complex a2) //Add 2 complex
numbers { return complex(a1.re+a2.re, a1.im+a2.im); }
ostream& operator<<(ostream& os, complex& cnum) //Output a complex
operator<< is accepting a non constant ostream& and a non constant complex=
&
number { os << "(" << cnum.re << "," << cnum.im << ") "; return os;
};
int main(void)
{ complex a(1,2), b(3,4); //Define complex numbe=
rs
cout <<"a=" << a <<",b=" << b <<" a+b = " << a+b << endl; /=
/Print
You are attempting to pass to operator<< a non constant ostream& and a non=
constant *temporary* complex& The temporary is the problem. Any chan=
ges
the function made to the temporary would be lost. A very simple fix. Ch=
ange
your operator<< to:
ostream& operator<<(ostream& os, const complex& cnum)
And your problem should go away.
You need to learn const correctness. A temporary rvalue can be passes a=
s a
const. I'm not sure of all the limitations, but it seems this is one of=
them. Your clue that this is a const correctness error is given in the
error itself:
"initial value of reference to ***non-const*** must be an lvalue".
sum
}
I also get the same warning in my compiler.
but I add some statement like:
//*********************************************************************
// CODE
//*********************************************************************
int a1=2;
int b1=3;
cout<<a1+b1;
this goes very well.
What's the difference between these two code? How can I get rid of
these warnings?
Thanks
--
Jim Langston
tazmas...@rocketmail.com- Hide quoted text -
- Show quoted text -- Hide quoted text -
- Show quoted text -
I am not getting any warning message with above code, using Visual
Studio 6.0 Compiler, You can create temporary object to hold result of
a+b, than pass temporary object to operator<<.
c= a+b;
cout<<c;
Regards,
Sachin