gpt4 book ai didi

c++ - 重载 << 运算符

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:54 27 4
gpt4 key购买 nike

<分区>

我刚刚为复数编写了一个类,您可以在下面看到它的代码;假设 A 和 B 是复数,我的问题是当我编写代码时:

cout << A+B; // it gives me an error

但是当我将 A+B 分配给 Complex 类的一个实例时,比如 C,它工作正常。我的意思是:

Complex C=A+B << endl; cout << C; // works correctly

我真的很困惑为什么我不能将 A+B 用作 << operator 的右操作数。任何想法我怎么能直接计算 A+B?在此先感谢您的帮助。这是我到目前为止的想法:

   #include <iostream>
using namespace std;

class Complex {
private:
double real;
double image;
public:

Complex(double r, double i){ real=r ; image=i;}

int GetReal(){ return real;}
int GetImage(){return image;}



//overload complex + complex
friend Complex operator+(const Complex &c1,const Complex &c2) ;
//overload complex + double
friend Complex operator+(const Complex &c,double Number) ;
//overload double + complex
friend Complex operator+(double Number,const Complex &c) ;

//overload complex * complex
friend Complex operator*(const Complex &c1, const Complex &c2);
//overload complex * double
friend Complex operator*(const Complex &c, double Number);
//overload double * complex
friend Complex operator*(double Number, const Complex &c);

//overloading output operator
friend ostream& operator<< (ostream &out, Complex &c);
};
Complex operator+(const Complex &c1,const Complex &c2){
return Complex(c1.real + c2.real,c1.image + c2.image);}

Complex operator+(const Complex &c,double Number){
return Complex(c.real + Number , c.image);}

Complex operator+(double Number,const Complex &c){
return Complex(Number + c.real,c.image);}

//(a + bi) * (c + di) = ((ac-bd) + (ad+bc)i)
Complex operator*(const Complex &c1, const Complex &c2){
return Complex(c1.real*c2.real-c1.image*c2.image,c1.real*c2.image+c1.image*c2.real);}

Complex operator*(const Complex &c, double Number){
return Complex(c.real*Number,c.image*Number);}

Complex operator*(double Number, const Complex &c){
return Complex(Number*c.real,Number*c.image);}

ostream& operator<< (ostream &out, Complex &c){
if( c.image>0){

out << c.real << "+ " <<
c.image << "i";}
else if (c.image==0){
out<<c.real;
}
else { out<< c.real<<"- "<<
c.image<< "i";}

return out;}

int main(){

Complex A(1,2);
Complex B(3,4);

cout<<"A is: "<<A<<endl;
cout<<"B is: "<<B<<endl;
Complex c=A+B;
cout<<c<<endl; //works correctly
cout<<A+B<<endl; // gives an Error ?!


}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com