#include <iostream>
using namespace std;
class A{
private:
int a;
public:
A(){}
A(int a_){a = a_;}
A(const A& A1){a = A1.a;}
setvalue(int v){a = v;}
int getvalue() const{return a;}
A& operator =(const A& A_);
};
//重载赋值运算符
A& A::operator =(const A& A_){
if(this!=&A_)
{
setvalue(A_.getvalue());
}
return *this;//返回当前对象的引用
}
int main()
{
A A1;
A1.setvalue(1);
A A2(A1);
cout <<"A1: " << A1.getvalue() << endl;
cout <<"A2: " << A2.getvalue() << endl;
A A3;
A A4(2);
A3 = A2 = A4;
cout <<"A4: " << A4.getvalue() << endl;
cout <<"A2: " << A2.getvalue() << endl;
cout <<"A3: " << A3.getvalue() << endl;
return 0;
}
注意事项:
- 将返回值的类型声明为该类型的引用,并在函数结束前返回实例自身的引用(*this),只有这样才可以连续赋值;
- 把传入的参数类型声明为常量引用。只可以引用传递,不可以值传递;
- 释放实例自身已有的内存;避免内存泄漏;
- 判断传入的参数和当前实例是不是同一个实例;
为什么int getvalue() const{return a;}要加const?
因为setvalue(A_.getvalue()); 实例A_是const,要调用const的实例的方法,必须将其方法也声明为const。否则,编译器会认为getvalue()方法可能会修改该实例,就会报错。