您的位置:首页 > 其它

两则const的使用引发的编译错误

2014-02-27 23:20 225 查看
1、将“const 类对象”作为函数的传入参数引起的问题

相关代码如下所示:

class CTest
{
public:
CTest(){ m_nValue = 0; }
virtual ~CTest(){ }

public:
int GetValue(){ return m_nValue; }
void SetValue( int nValue ){ m_nValue = nValue; }

private:
int m_nValue;
};

void TestFun( const CTest& test )
{
int nValue = test.GetValue(); // 此行为报错的代码行
}

void main()
{
CTest test;
TestFun( test );
}
上述的代码编译会报这样的错误:error C2662: “CTest::GetValue”: 不能将“this”指针从“const CTest”转换为“CTest &”。const CTest& test相当于一个const对象,由于const对象在调用成员函数的时候,会将this指针强行转换为const this,所以它将无法找到相应的show() const函数,并且编译器也无法将一个const的对象转化为一个普通对象来调用普通的show()方法,所以就会产生上述的编译错误。
其实,更进一步分析,对于一个类要做到const对象的只不改变,不仅仅是在类对象前加上const关键字,主要还是靠const函数实现类对象的数据成员的不可改变。所以就很好理解,CString也是一个类,为什么CString可以做上述的代码处理,而CTest则不行了。因为CString提供给外部调用的部分函数是const函数。那为什么CString提供的部分接口不是const函数呢?因为有些函数就是要来修改类中的字符串的。

2、const函数里面不能调用非const函数

相关代码如下所示:

class CTest
{
public:
CTest(){ m_nValue = 0; }
virtual ~CTest(){ }

public:
int GetValue() { return m_nValue; }

bool CheckValue() const
{
int nValue = GetValue(); // 此行为报错的代码行
return nValue>0;
}

private:
int m_nValue;
};
上述的代码编译也会报类似的错误:error C2662: “CTest::GetValue”: 不能将“this”指针从“const CTest”转换为“CTest &”。原因是这样子的:CheckValue是const函数,是要保证该函数不修改类的数据成员,但是函数中调用了非const函数GetValue,而非const函数可能会修改数据成员,所以编译器给出了上述的错误。也就是说,const函数里面不能调用非const函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: