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条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码