两则const的使用引发的编译错误
2014-02-27 23:20
225 查看
1、将“const 类对象”作为函数的传入参数引起的问题
相关代码如下所示:
其实,更进一步分析,对于一个类要做到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; } 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函数。
相关文章推荐
- 在gradle中使用greenDao引发的多重编译错误
- 在const成员函数中使用下标[]操作map成员引发编译错误
- JUERY的Ajax方法在ASP.NET 下使用引发的页面错误
- 由app group引发的编译错误
- 使用VS 2008(带sp1)编译VC 6.0的一个工程,出现下面的编译错误
- 使用vs2008 的OutputDebugString 时编译产生的错误
- 使用cocos 命令编译项目简单错误识记
- 在ubuntu下使用Qt 编译时候遇上了cannot find -lGL错误
- Android 使用全局的静态变量,引发一系列诡异错误
- 【mfc】vc++ 使用64位平台编译,运行程序出现0xc000007b错误的解决方案
- 使用 Cocoapods 集成框架 Operation not permitted - /usr/bin/xcodeproj,以及项目出现 Invalid bitcode signature 编译错误
- 使用studio编译中遇到的两个的错误_'D:\jdk1.7.0_80\bin\java.exe'' finished with non-zero exit value 1 等
- 下载使用CocoaPods的开源项目时,编译出现错误解决方法
- osx使用cmake编译opencv错误记录
- Linux系统平台下关于GCC编译及使用的方法(-Werror,它要求GCC将所有的警告当成错误进行处理 )
- android Context错误使用引发的内存泄露
- 使用flashdevelop时,MXML文件中带有中文时编译错误问题解决
- android源码编译使用proguard文件进行混淆及错误总结
- Xcode使用[XCTestCase]测试因Mach-O Type引发的错误
- VS2008 编译 链接器错误以及使用C语言函数的警告