error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
来源:互联网 发布:北京java程序员招聘 编辑:程序博客网 时间:2024/05/18 12:44
先看一下导致这个编译错误的例子:
class COwnInt
{
public:
int get();
private:
int m_n;
};
int COwnInt::get()
{
return m_n;
}
int main()
{
const COwnInt own;
own.get();
return 0;
}
这个编译错误的主要原因是:程序中定义了一个const的类对象own,然后又用own调用了一个非const的函数get()。
由于const对象在调用成员函数的时候,会将this指针强行转换为const this,所以它将无法找到相应的const get函数,并且编译器也无法将一个const的对象转化为一个普通对象来调用这个普通的get方法,所以就会产生如题的编译错误。
至于const的用法,我们已经已经在C++/const详解中详细的介绍了const的用法,这里就不再赘述。
解决方法是:将get()函数修改为const函数,也就是这样:
class COwnInt
{
public:
int get() const; //将get函数声明为const型
private:
int m_n;
};
int COwnInt::get() const //请注意,这里也要追加const关键字
{
return m_n;
}
当然,还有一个解决方法是将const COwnInt own改成COwnInt own。
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’的解决办法
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- The resolution of ERROR C2662: cannot convert 'this' pointer from "const Class-Type" to "Class&"
- cannot convert 'this' pointer from 'const class Rational' to 'class Rational &' 是什么意思
- 关于C++ error C2662 cannot convert 'this' pointer from...
- cannot convert 'this' pointer from 'const cl
- find_if 仿函数错误:cannot convert 'this' pointer from 'const CActTaskData' to 'CActTaskData &'
- cannot convert parameter 1 from 'class A' to 'class A'
- cannot convert parameter from 'class CStdioFile' to 'class CStdioFile'
- 错误:Type mismatch: cannot convert from Class<SpringJUnit4ClassRunner> to Class<? extends Runner>
- Type mismatch: cannot convert from Class<SpringJUnit4ClassRunner> to Class<? extends Runner>
- Cannot convert from 'const char [..]' to 'LPCTSTR'
- Cannot convert from 'const char [..]' to 'LPCTSTR'
- XCode里插入调试断点,程序却不停止的解决方法
- 搭建交叉编译环境
- 自己动手实现IOC和MVC(一)
- panel 误删
- 2012校招之创新工厂远程面试
- error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- html和winform交互
- Release版本如何调试
- 网页中屏蔽右键方法
- PHP开发SOAP注意点
- 开源软件编译
- ant build.xml文档编写
- 如何启用 Ubuntu 中的 root 帐号
- c# asp.net webservice asmx中保存HttpContext.Current