运算符继承

mic*_*t38 3 c++

我有以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

没问题,cout << (s1 + s2).area();但在s1 = s1 + s2;编译器给我一个错误:

不匹配“operator=”(操作数类型为“Square”和“Rectangle”)

为什么这条线不起作用?

Evg*_*Evg 6

如果您不提供赋值运算符,编译器将为声明一个。在这里,编译器生成Square::operator=(const Square&). 赋值运算符 fromRectangle被此运算符隐藏。您可以Rectangle::operator=使用using声明带入范围:

class Square : public Rectangle
{
public:
    using Rectangle::operator=;

    // ...
};
Run Code Online (Sandbox Code Playgroud)

现在代码可以编译了,但是有缺陷。正如 Konrad Rudolph、Jarod42 和 molbdnilo 在评论中所指出的,SquareRectangle逻辑上推导是错误的,因为它违反Liskov 的替换原则。您现在可以将 a 分配Rectangle给 a Square,而这样的分配没有意义。

  • 这是逻辑错误,`矩形 r(1, 3); 平方 s(1);s = r;`...有一个正方形,而不是正方形。 (3认同)