我有以下代码:
class Rectangle
{
protected:
int a, b;
public:
Rectangle(int a, int b) : a(a), b(b) {}
int area() { return a*b; }
Rectangle operator+(const Rectangle & other)
{
Rectangle temp(0, 0);
temp.a = a + other.a;
temp.b = b + other.b;
return temp;
}
void operator=(const Rectangle & other)
{
a = other.a;
b = other.b;
}
};
class Square : public Rectangle
{
public:
Square(int a) : Rectangle(a, a) {}
};
int main()
{
Square s1(3);
Square s2(1);
cout << (s1 + s2).area();
s1 = s1 + s2;
}
cout << (s1 + s2).area();
可以,但在 s1 = s1 + s2;
编译器给我一个错误:
no match for 'operator=' (operand types are 'Square' and 'Rectangle')
为什么这条线不起作用?
最佳答案
如果您不提供赋值运算符,则编译器 will declare一个给你。此处,编译器生成 Square::operator=(const Square&)
。 Rectangle
中的赋值运算符被此运算符隐藏。您可以使用 using
declaration 将 Rectangle::operator=
带入范围内:
class Square : public Rectangle
{
public:
using Rectangle::operator=;
// ...
};
现在代码可以编译,但是有缺陷。正如 Konrad Rudolph、Jarod42 和 molbdnilo 在评论中指出的那样,从 Rectangle
派生 Square
在逻辑上是错误的,因为它 violates Liskov's substitution principle .您现在可以将 Rectangle
分配给 Square
,这样的分配没有任何意义。
关于c++ - 运算符继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61383936/