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则不行了。因为CSt