c++ 错误 C2662 无法将“this”指针从“const Type”转换为“Type &”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12068301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ error C2662 cannot convert 'this' pointer from 'const Type' to 'Type &'
提问by thiagoh
I am trying to overload the c++ operator== but im getting some errors...
我正在尝试重载 c++ 运算符==但我遇到了一些错误...
error C2662: 'CombatEvent::getType' : cannot convert 'this' pointer from 'const CombatEvent' to 'CombatEvent &'
错误 C2662:“CombatEvent::getType”:无法将“this”指针从“const CombatEvent”转换为“CombatEvent &”
this error is at this line
这个错误在这一行
if (lhs.getType() == rhs.getType())
see the code bellow:
看下面的代码:
class CombatEvent {
public:
CombatEvent(void);
~CombatEvent(void);
enum CombatEventType {
AttackingType,
...
LowResourcesType
};
CombatEventType getType();
BaseAgent* getAgent();
friend bool operator<(const CombatEvent& lhs, const CombatEvent& rhs) {
if (lhs.getType() == rhs.getType())
return true;
return false;
}
friend bool operator==(const CombatEvent& lhs, const CombatEvent& rhs) {
if (lhs.getType() == rhs.getType())
return true;
return false;
}
private:
UnitType unitType;
}
can anybody help?
有人可以帮忙吗?
回答by hcarver
CombatEventType getType();
needs to be
需要是
CombatEventType getType() const;
Your compiler is complaining because the function is being given a const
object that you're trying to call a non-const
function on. When a function gets a const
object, all calls to it have to be const
throughout the function (otherwise the compiler can't be sure that it hasn't been modified).
您的编译器正在抱怨,因为该函数被赋予了一个const
您试图在其上调用非const
函数的对象。当一个函数获得一个const
对象时,对它的所有调用都必须const
贯穿整个函数(否则编译器不能确定它没有被修改)。
回答by Andrzej
change the declaration to :
将声明更改为:
CombatEventType getType() const;
you can only call 'const' members trough references to const.
您只能通过对 const 的引用来调用“const”成员。
回答by daz-fuller
It's a const issue, your getType method is not defined as const but your overloaded operator arguments are. Because the getType method is not guaranteeing that it will not change the class data the compiler is throwing an error as you can't change a const parameter;
这是一个 const 问题,您的 getType 方法未定义为 const 但您的重载运算符参数是。因为 getType 方法不能保证它不会更改类数据,所以编译器会抛出错误,因为您无法更改 const 参数;
The simplest change is to change the getType method to
最简单的更改是将 getType 方法更改为
CombatEventType getType() const;
Unless of course the method is actually changing the object.
当然,除非该方法实际上正在更改对象。