c++学校oj题目分析

代码:

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

class Complex
{
public:
	double r; // real
	double i; // image
public:
	Complex() :r(0), i(0) {}
	Complex(double a, double b) :r(a), i(b) {}
	void Show() const
	{
		cout << "(" << noshowpos << r << showpos << i << noshowpos << "i)" << endl;
	}

	Complex(Complex& d1)
	{
		r = d1.r * 2;
		i = d1.i * 2;
	}

	Complex operator=(const Complex& d1)
	{
		r = 3 * d1.r;
		i = 3 * d1.i;
		return *this;
	}
};

int main()
{
	double a, b;
	cin >> a >> b;

	Complex c1(a, b);
	Complex c3 = c1;
	Complex c4, c5;
	c5 = c4 = c1;
	const Complex& c6 = c4 = c1;

 	c1.Show();
	c3.Show();
	c4.Show();
	c5.Show();
	c6.Show();

	return 0;
}

1、为什么赋值运算符重载必须加const,否则编译器报错

因为c1赋值的c4的时候会创建一份临时变量,而c5则被这个临时变量赋值,因为是个临时变量,所以是const的,如果赋值运算符参数不加const,则const传给非const参数,权限扩大,就会发生报错

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一起慢慢变强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值