1.常量不能为左值
cannot convert 'this' pointer from 'const class X' to 'class X &'
例子:
#include <iostream.h>
class X
{
int i;
public:
void modify() {cout<<"haha"<<endl;}
};
const class X fun(){return X();}
void main()
{
//fun().modify(); //常量不能为左值,所以下例也不成立:
//error C2662: 'modify' : cannot convert 'this' pointer from 'const class X' to 'class X &'
const X g = X();
g.modify();
}
解决方案
void modify() const {cout<<"haha"<<endl;}
2. 类常量成员初始化 (用初始化成员列表)
class Y{
public:
const size;
Y();
};
Y::Y():size(100){}
class X{
enum{i=100};
};