我在继承 operator= 时遇到问题。为什么这段代码不起作用,修复它的最佳方法是什么?
#include <iostream>
class A
{
public:
A & operator=(const A & a)
{
x = a.x;
return *this;
}
bool operator==(const A & a)
{
return x == a.x;
}
virtual int get() = 0; // Abstract
protected:
int x;
};
class B : public A
{
public:
B(int x)
{
this->x = x;
}
int get()
{
return x;
}
};
class C : public A
{
public:
C(int x)
{
this->x = x;
}
int get()
{
return x;
}
};
int main()
{
B b(3);
C c(7);
printf("B: %d C: %d B==C: %d\n", b.get(), c.get(), b==c);
b = c; // compile error
// error: no match for 'operator= in 'b = c'
// note: candidates are B& B::operator=(const B&)
printf("B: %d C: %d B==C: %d\n", b.get(), c.get(), b==c);
return 0;
}