代码:
#define _CRT_SECURE_NO_WARNINGS #include#include #include 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参数,权限扩大,就会发生报错



