c++ - 运算符继承

标签 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;
}

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 declarationRectangle::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/

相关文章:

c++ - 返回对 std::function-wrapped lambda 中静态变量的引用会导致段错误

c++ - 在 C++ 中创建类型未知的模板 vector (空模板)

具有线程安全队列的 C++11 事件循环

c++ - Doxygen:是否可以去除 CHM 索引中的命名空间名称?

c++ - 为处理器执行除法和取模的最佳方法是什么?

c++ - msys2 静态 QT undefined reference 问题

c++ - 重载 C++ 类型以处理自定义类

c++ - 如何通过程序清除某个站点的IE缓存

c++ - 如何将字符串变量名转换为变量的值

c++ - 获取时间复杂度错误