Hi,
I'm almost a newbie to C++. I have a problem that i can't figure out. Hope you can help.
I have a class A and i define the operator + for this class, like this :
A operator+ (const A& x, const A& y) { ... }
Then i define operator overloading for << , like this :
ostream& operator<<(ostream& out, A& x ) { ... }
I run
cout << x // x is A object
then it works fine.
The problem is, when i run
cout << x + y // x,y are A object
then it produces error. It says : " no match for operator << ..... "
I dont know why the compiler doesn't recognize x+y as an A object.
Any help ?
Last edited on
i'm Sopheaktra , Cambodian
Could You please tell me how to overload with opeator New....
Thank...
I use g++. I have used your code but it still failed.
I change
ostream operator<<(ostream& out, A&x)
to
ostream operator<<(ostream&out, A x)
then it works : )
Athough happy , i still dont know why the first doesn't work but when i ignore the '&' then it works ?
Anyone know ?
Last edited on
Can anyone give me, the g++ compiler.... Post it to pheaktra_num@yahoo.com
thank...
I think it's because your A si not const... personally I use in my class definition :
friend std::ostream& operator<<(std::ostream &out, const A&x);
And it works.
If I remember well, you can't overload the new operator...
Last edited on
class Complex {
public:
Complex( double = 0.0, double = 0.0 ); // constructor
Complex operator+( const Complex & ) const; // addition
Complex operator-( const Complex & ) const; // subtraction
void print() const; // output
private:
double real; // real part
double imaginary; // imaginary part
}; // end class Complex
// Constructor
Complex::Complex( double realPart, double imaginaryPart )
: real( realPart ), imaginary( imaginaryPart )
{
// empty body
} // end Complex constructor
// addition operator
Complex Complex::operator+( const Complex &operand2 ) const
{
return Complex( real + operand2.real,
imaginary + operand2.imaginary );
} // end function operator+
// subtraction operator
Complex Complex::operator-( const Complex &operand2 ) const
{
return Complex( real - operand2.real,
imaginary - operand2.imaginary );
} // end function operator-
// display a Complex object in the form: (a, b)
void Complex::print() const
{
cout << '(' << real << ", " << imaginary << ')';
} // end function print
int main()
{
Complex x;
Complex y( 4.3, 8.2 );
Complex z( 3.3, 1.1 );
cout << "x: ";
x.print();
cout << "\ny: ";
y.print();
cout << "\nz: ";
z.print();
x = y + z;
cout << "\n\nx = y + z:" << endl;
x.print();
cout << " = ";
y.print();
cout << " + ";
z.print();
x = y - z;
cout << "\n\nx = y - z:" << endl;
x.print();
cout << " = ";
y.print();
cout << " - ";
z.print();
cout << endl;
return 0;
} // end main
Can anyone tell me how to modify the class to enable input and output of complex numbers through the overloaded >> and << operators, respectively?