c++;错误C2662无法转换';这';来自';常量类型';至';类型及'; 我试图重载C++运算符==,但是我得到了一些错误……p>
错误C2662:“CombatEvent::getType”:无法将“this”指针从“const CombatEvent”转换为“CombatEvent&” 此错误位于此行c++;错误C2662无法转换';这';来自';常量类型';至';类型及'; 我试图重载C++运算符==,但是我得到了一些错误……p>,c++,operator-overloading,syntax-error,friend-function,C++,Operator Overloading,Syntax Error,Friend Function,错误C2662:“CombatEvent::getType”:无法将“this”指针从“const CombatEvent”转换为“CombatEvent&” 此错误位于此行 if (lhs.getType() == rhs.getType()) 请参见下面的代码: class CombatEvent { public: CombatEvent(void); ~CombatEvent(void); enum CombatEventType { Att
if (lhs.getType() == rhs.getType())
请参见下面的代码:
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;
}
类CombatEvent{
公众:
CombatEvent(无效);
~CombatEvent(无效);
枚举CombatEventType{
攻击类型,
...
低资源型
};
CombatEventType getType();
BaseAgent*getAgent();
友人布尔算子
需要
CombatEventType getType() const;
您的编译器正在抱怨,因为函数被赋予了一个const
对象,而您正试图在该对象上调用一个非const
函数。当函数获得const
对象时,在整个函数中对它的所有调用都必须是const
(否则编译器无法确保它没有被修改).将声明更改为:
CombatEventType getType() const;
您只能通过引用const来调用'const'成员。这是一个const问题,您的getType方法没有定义为const,但重载的运算符参数却定义为const。因为getType方法不能保证它不会更改类数据,所以编译器会抛出一个错误,因为您无法更改const参数
最简单的更改是将getType方法更改为
CombatEventType getType() const;
当然,除非该方法实际上正在更改对象。我在下面的代码中看到了这个错误
get_color(const std::unsigned_integral auto &x,
const std::unsigned_integral auto &y,
const BPPT & depth,
const std::unsigned_integral auto &palette = 0U,
const std::unsigned_integral auto &texture_id = 0U) const
当我改为模板时,它工作了
template<std::unsigned_integral xT,
std::unsigned_integral yT,
std::unsigned_integral paletteT,
std::unsigned_integral texture_idT>
[[nodiscard]] Color16
get_color(const xT x,
const yT y,
const BPPT depth,
const paletteT palette = 0U,
const texture_idT texture_id = 0U) const
模板
[[nodiscard]]颜色16
获取颜色(常数xT x,
康斯特yT y,
常量BPPT深度,
常数调色板=0U,
常量纹理\u idT纹理\u id=0U)常量
template<std::unsigned_integral xT,
std::unsigned_integral yT,
std::unsigned_integral paletteT,
std::unsigned_integral texture_idT>
[[nodiscard]] Color16
get_color(const xT x,
const yT y,
const BPPT depth,
const paletteT palette = 0U,
const texture_idT texture_id = 0U) const