gpt4 book ai didi

c++ - 编译问题相等/不等运算符

转载 作者:太空宇宙 更新时间:2023-11-04 16:30:23 25 4
gpt4 key购买 nike

我有以下代码序列而且我不明白编译错误(代码下方)。

提前致谢

尤利安

class X {
public:

int a;

X()
{
a = 0;
}

bool operator == (const X&r)
{
return a == r.a;
}

bool operator != (const X&r)
{
return !( *this == r );
}
};

class DX : public X
{
public:
int dx;
DX()
{
dx = 1;
}

bool operator == (const DX&r)
{

if( dx != r.dx ) return false;
const X * lhs = this;
const X * rhs = &r;

if ( *lhs != *rhs ) return false;

return true;
}

bool operator != (const DX&r)
{
return !( *this == r );
}
};

int main(void)
{
DX d1;
DX d2;
d1 == d2;
return 0;
}

错误:

d:\Projects\cpptests>cl opequal.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved.

opequal.cpp opequal.cpp(38) : error C2678: binary '!=' : no operator found which takes a lef t-hand operand of type 'const X' (or there is no acceptable conversion) opequal.cpp(16): could be 'bool X::operator !=(const X &)' while trying to match the argument list '(const X, const X)'

最佳答案

您需要将 operator==operator!= 函数声明为常量。

例如。

bool operator == (const X&r) const

关于c++ - 编译问题相等/不等运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7764271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com