#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
悬赏问题
- ¥15 三极管电路求解,已知电阻电压和三级关放大倍数
- ¥15 ADS时域 连续相位观察方法
- ¥15 Opencv配置出错
- ¥15 模电中二极管,三极管和电容的应用
- ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
- ¥15 气象网格数据与卫星轨道数据如何匹配
- ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
- ¥15 微软账户问题不小心注销了好像
- ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
- ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused