次のコードシーケンスがあります。コンパイルエラー(コードの下にあります)がわかりません。事前にコンパイルの問題等価/不等式演算子
おかげで、
イウリアン
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)'
'=='と '=='の形で '!='と '!='を定義しようとしていますが、 '=='の中に '!=まだ定義されていません。すべての演算子を 'const'にする必要があります。 –
警告:等価演算子を空き関数として宣言することをお勧めします。 '(X(1)== DX())<==>(DX()== X(1))'はこのように保証するのは難しいです。 – xtofl