Chen_Ge_ 2021-03-31 10:43 采纳率: 100%
浏览 43
已采纳

c++重载输出流运算符

#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行会报错;
*/
  • 写回答

2条回答 默认 最新

  • 502203305 2021-03-31 10:58
    关注

    重载运算符使用 const CComplex&类型,报错是因为传入是一个临时的消亡值.需要用const的方式延长生命周期.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵