您的位置:首页 > 编程语言 > C语言/C++

c++ const 成员函数

2009-10-14 22:03 239 查看
const对象不能调用非const成员函数

class test
{
int n;
public:
test(int m){n=m;}
int getval(){return n;}
};
int main ()
{
const test a(2);
a.getval(); //error
return 0;
}


vc2005提示错误为:

error C2662: 'test::getval' : cannot convert 'this' pointer from 'const test' to 'test &'

说明成员函数的this指针类型为test * 或test & 不能由const test * 或const test赋值.

解决方法:

getval加上const属性或者对a进行const_cast .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: