在编译程序的时候出现了如下的错误:
正在编译... 1>Session.cpp 1>e:\comm\commserver\session.cpp(24) : error C2662: 'Session::getSock' : cannot convert 'this' pointer from 'const Session' to 'Session &' ...................................
Error Message 'function' : cannot convert 'this' pointer from 'type1' to 'type2' The compiler could not convert the this pointer from type1 to type2. This error can be caused by invoking a non-const member function on a const object. Possible resolutions: Remove the const from the object declaration. Add const to the member function.
无法将this指针从类型type1转换成类型type2. 产生问题的原因常常是用一个const类型的对象去调用它的非const类型的成员函数。方法1:对象的const修饰符去掉 方法2:将调用的函数改成const函数。
根据MSDN的解释,就知道了。
我的getSock函数声明如下:
Socket getSock();
而调用的环境是:
Session& Session::operator=(const Session &session) { m_sock = session.getSock(); //....... return *this; }
看到了,对象session是一个const对象,但是getSock函数是一个非const成员函数。
Socket getSock()const;
并对实现做相应修改。则编译通过。
编译器做了一个限制,const对象只能调用const成员函数,因为const成员函数是不能修改属性的,这种操作安全。
对象调用成员函数,会传递指针A* const this(A是类型),但是const对象调用成员函数时会做如下转化:
const A * const this. 这种情况下,任何对成员的修改都会报错,因为this指向的那个对象也用了const修饰。用const修饰,就是为了施加一种约束,可以在编译时发现错误,而不是在运行期发现。
在const对象调用成员函数时,编译器会认为调用的函数是const类型。但由于实际不是,所以类型不匹配,会报错。
这个测试代码从网上摘的:
class Point3d { public: Point3d(float x=0.0,float y=0.0,float z=0.0) :_x(x),_y(y),_z(z) { } float GetX() {return _x;} float GetY() {return _y;} float GetZ() {return _z;} private: float _x,_y,_z; }; inline ostream& operator<<(ostream&out,const Point3d& pd) { out<<pd.GetX()<<endl; return out; }
编译报错(codeblock minGW):
G:\sourceCode\constTest\constTest\main.cpp|23|error: passing 'const Point3d' as 'this' argument
of 'float Point3d::GetX()' discards qualifiers|
discards qualifiers的意思是丢弃了限定符。可以这么理解,pd.GetX()操作时,由于pd是const对象,所以认为调用的GetX()是这样的:
float GetX() const {return _x;}
但是实际上这个函数是没有const修饰符的。所以提示修饰符被丢弃了。提醒你,加上修饰符啊。