首页 > 其他 > 详细

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

时间:2014-02-28 22:34:56      阅读:498      评论:0      收藏:0      [点我收藏+]

        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函数。

两则const的使用引发的编译错误,布布扣,bubuko.com

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

原文:http://blog.csdn.net/chenlycly/article/details/20081669

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!