thi*_*goh 23 c++ operator-overloading syntax-error friend-function
我试图重载c ++运算符==但我得到一些错误...
错误C2662:'CombatEvent :: getType':无法将'this'指针从'const CombatEvent'转换为'CombatEvent&'
这个错误就在这一行
if (lhs.getType() == rhs.getType())
Run Code Online (Sandbox Code Playgroud)
看下面的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮忙吗?
hca*_*ver 54
CombatEventType getType();
Run Code Online (Sandbox Code Playgroud)
需要是
CombatEventType getType() const;
Run Code Online (Sandbox Code Playgroud)
你的编译器抱怨,因为函数被赋予了const你试图调用非const函数的对象.当函数获取一个const对象时,对它的所有调用都必须const遍及整个函数(否则编译器无法确定它是否未被修改).
将声明更改为:
CombatEventType getType() const;
Run Code Online (Sandbox Code Playgroud)
你只能通过引用const来调用'const'成员.
这是一个const问题,你的getType方法没有被定义为const,但你的重载运算符参数是.因为getType方法不保证它不会更改类数据,所以编译器会抛出错误,因为您无法更改const参数;
最简单的更改是将getType方法更改为
CombatEventType getType() const;
Run Code Online (Sandbox Code Playgroud)
除非该方法实际上是在改变对象.
| 归档时间: |
|
| 查看次数: |
36745 次 |
| 最近记录: |