您的位置:首页 > 移动开发 > Objective-C

const对象调用非const成员函数

2010-01-18 16:44 405 查看
第一种情况:const对象调用非const成员函数

class A
{
public:
A(int N = 0);
void Fun();
private:
int n;
};
A::A(int N):n(N)
{
}
void A::Fun()
{
cout << n << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a.Fun();

const A &b = a;
b.Fun();//const引用的对象调用非const成员函数

//const A a;
//a.Fun();//const对象调用非const成员函数

cin.get();
return 0;
}


当使用const对象调用非const成员函数时编译会报错:error C2662: 'A::Fun' : cannot convert 'this' pointer from 'const A' to 'A &'

报错原因:因为const对象在调用成员函数时会隐含的把实参把中*this修改成const class * const this,以导致非const成员函数在接收时还是使用了class *const this接收,结果就是把const的指针赋给非const的指针

修正方法:以前错误只需在对象的成员函数后面加上const即可

 

class A
{
public:
A(int N = 0);
void Fun() const;
private:
int n;
};
A::A(int N):n(N)
{
}
void A::Fun() const
{
cout << n << endl;
}


 

第二种情况:在const成员函数中修改非const成员

class A
{
public:
A(int N = 0);
void Fun() const;
protected:
private:
int n;
};
A::A(int N):n(N)
{
}
void A::Fun() const
{
n = 100;//在const成员函数中修改了成员变量n的值
cout << n << endl;
}


同样,在编译此类时会报错:error C2166: l-value specifies const object

原因:在const的成员函数中修改了成员变量的值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  fun class object c