I have the following code sequence And I don’t understand the compilation error (below the code).
Thanks in advance,
Iulian
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;
}
The error:
d:\Projects\cpptests>cl opequal.cpp Microsoft (R) 32-bit C/C++
Optimizing Compiler Version 15.00.30729.01 for 80×86 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)’
You need to declare your
operator==andoperator!=functions as const.Eg.