const对象调用非const成员函数
2010-01-18 16:44
405 查看
第一种情况:const对象调用非const成员函数
当使用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即可
第二种情况:在const成员函数中修改非const成员
同样,在编译此类时会报错:error C2166: l-value specifies const object
原因:在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的成员函数中修改了成员变量的值
相关文章推荐
- const成员函数和非const的成员函数之间的调用
- 非const对象也可以调用const成员函数
- 非const对象也可以调用const成员函数
- const对象调用static成员函数
- const成员函数和const对象的调用关系
- 【C++总结】函数形参,返回const对象与非const对象,成员函数,函数指针
- C++中const成员函数和非const成员函数的重载
- const变量、const指针、const参数、const对象、const成员函数
- egg egg::E(100);静态成员(对象)是如何调用非静态的、私有的成员(构造)函数的呢?
- 成员函数对象类的const和非const成员函数的重载
- C++类对象内存模型与成员函数调用分析(下)
- 使用对象调用成员函数
- C++匿名对象调用成员函数
- const成员函数和非const成员函数返回引用的问题
- 为什么可以不创建对象就调用类的成员函数?
- const修饰成员函数const修饰对象
- const 对象只能调用 const 函数
- JavaScript中对象调用其他函数/对象成员
- C++类对象内存模型与成员函数调用分析(上)
- 什么时候调用const版本的成员函数