以一段代码来说明
class Byte{
unsigned uchar b;
public:
Byte(uchar b1=0):b(b1){}
//+
const Byte operator +(const Byte &right) const{
return Byte(b+right.b);
}
//赋值
Byte& operator =(const Byte &right){
if(this==&right)
return *this;
b=right.b;
return *this;
}
};
const(1) Byte operator +(const(2) Byte &right) const(3) 中
- const(3) const修饰成员函数,有两点规则:const修饰的成员函数不能修改任何成员变量;
- const成员函数不能调用非const成员函数,因为非const成员函数可能会改变成 员变量的值。
- 在重载+时,没有改变操作数的值,没有改变成员变量,所以使用const修饰成员函数
- 而重载赋值运算符时,b=right.b改变了成员变量b,不能用const修饰成员函数。
- const(2) const修饰函数参数,并且函数参数为常引用,传递的参数在函数内不可改变
- const(1) const修饰函数返回值 ,有两种情况:
如果返回的是pointer或者&,比如
const A& function(int x){
return A(a+b);//a是A的数据成员
}
此时成为返回后就成为const A &A(a+b),常引用,A(a+b)就成为常量不能通过引用来修改。在重载赋值运算符时,返回*this,最好不用const*修饰
如果返回值采用值传递,加const意义不大,不加也可。