#include <iostream>
using namespace std;
class CComplex {
public:
CComplex();
CComplex(double x, double y);
CComplex(double R);
friend CComplex operator + (CComplex& obj1, CComplex& obj2);
friend CComplex operator - (CComplex& obj1, CComplex& obj2);
friend CComplex operator * (CComplex& obj1, CComplex& obj2);
friend CComplex operator / (CComplex& obj1, CComplex& obj2);
friend ostream& operator << (ostream& output, CComplex& C);
private:
double real;
double imag;
};
CComplex::CComplex() {
real = 0.0;
imag = 0.0;
}
CComplex::CComplex(double x, double y) {
real = x;
imag = y;
}
CComplex::CComplex(double R) {
real = R;
imag = 0;
}
CComplex operator + (CComplex& obj1, CComplex& obj2) {
CComplex obj3(obj1.real + obj2.real, obj1.imag + obj2.imag);
return obj3;
}
CComplex operator - (CComplex& obj1, CComplex& obj2) {
CComplex obj3(obj1.real - obj2.real, obj1.imag - obj2.imag);
return obj3;
}
CComplex operator * (CComplex& obj1, CComplex& obj2) {
CComplex obj3(obj1.real * obj2.real - obj1.imag * obj2.imag, obj1.real * obj2.imag - obj2.real * obj1.imag);
return obj3;
}
CComplex operator / (CComplex& obj1, CComplex& obj2) {
if (obj2.real == 0 && obj2.imag == 0) { cout << "Wrong!" << endl; exit(0); }
CComplex obj3((obj1.real * obj2.real - obj1.imag * (-obj2.imag)) / (obj2.real * obj2.real + obj2.imag * obj2.imag),
obj1.real * (-obj2.imag) - obj2.real * obj1.imag / (obj2.real * obj2.real + obj2.imag * obj2.imag));
return obj3;
}
ostream& operator << (ostream& output, CComplex& C) {
output << C.real << " + " << C.imag << "i";
return output;
}
int main()
{
CComplex c1 = 5;
CComplex c2 = 0;
CComplex c3 = CComplex(3, 4);
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
CComplex c4 = c1 + c3;
cout << c4 << endl;
CComplex c5 = c1 - c3;
cout << c5 << endl;
CComplex c6 = c1 * c3;
cout << c6 << endl;
CComplex c7 = c1 / c3;
cout << c7 << endl;
//cout << ( c1 + c3 ) << endl;
//cout << c1 + c3 << endl;
return 0;
}
/*
提问:
1.为什么71,72行会报错;
*/

c++重载输出流运算符
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- 「已注销」 2021-03-31 10:58关注
重载运算符使用 const CComplex&类型,报错是因为传入是一个临时的消亡值.需要用const的方式延长生命周期.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用 2