class Rectangle
{
public:
string what();
friend ostream& operator <<(ostream& os,const Rectangle &object);
};
ostream& operator << (ostream& os,const Rectangle& object)
{
os << object.what() <<": width = " << object.width << ", height = " << object.height << endl;
return os;
}
最近在做c++的课程设计实验,设计要求很easy,但是遇到了一个很奇怪的问题,编译时报错passing ‘const Rectangle’ as ‘this’ argument of ‘Rectangle::what()’ discards qualifiers。比对书上的例子始终找不到原因所在,网上发现了有人有同样的问题,点击打开链接。
翻译过来就是说:
一个const对象不能调用它的non-const成员函数,只能使用const成员。即使成员函数并没有改变对象成员的值,编译器也会以为其改变了对象。为了解决这个问题,只需将const对象所需要用到的成员函数const即可。
由此可见,c++中const是一个神奇又略复杂的东西,我的c++之路还有很长一段路要走。