VS2005下错误error C2662的解决

1. 错误来源:

在编译程序的时候出现了如下的错误:

正在编译...
1>Session.cpp
1>e:\comm\commserver\session.cpp(24) : error C2662: 'Session::getSock' : cannot convert 'this' 
pointer from 'const Session' to 'Session &'
...................................

2. 错误编号的解释:

看错误提示说:函数getSock无法将 this指针从const Session类型转换成Session& 类型。
没看明白,看MSDN的解释
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函数。

3. 解决方法

根据MSDN的解释,就知道了。
我的getSock函数声明如下:

Socket getSock();

而调用的环境是:

Session& Session::operator=(const Session &session)
{
	m_sock = session.getSock();
	//.......
	
	return *this;
}

看到了,对象session是一个const对象,但是getSock函数是一个非const成员函数。
对getSock()函数的声明修改如下:
Socket getSock()const;

并对实现做相应修改。则编译通过。

4.为什么const对象不能调用非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修饰符的。所以提示修饰符被丢弃了。提醒你,加上修饰符啊。

转载于:https://my.oschina.net/myspaceNUAA/blog/59256

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值