今天写了一段程序,发现了一个自己之前没有注意到的点。在此记录下
#include <iostream>
class Base
{
public:
Base(int x)
{
this->m_x = x;
}
int& Getx()
{
return this->m_x;
}
void Setx(int x)
{
this->m_x = x;
}
private:
int m_x;
};
int main(void)
{
Base base(1);
std::cout << base.Getx() <<std::endl;//1
base.Getx() = 10;
std::cout << base.Getx() << std::endl;//10
int& x = base.Getx();
x = 0;
std::cout << base.Getx() << std::endl;//0
return 0;
}
上述程序可以看出来,通过对成员函数赋值,竟然可以改变类的私有数据成员。
所以针对成员函数返回值是引用类型时,我们可以加const来避免这种问题
const int& Getx()
{
return this->m_x;
}
这样添加后,再次编译就会报错了,因为const类型无法改变成其他值