【问题标题】:Why are Liskov Substitution Principle violations not shown in this C++ snippet?为什么这个 C++ 代码片段中没有显示违反 Liskov 替换原则的情况?
【发布时间】:2015-01-21 02:44:26
【问题描述】:

我尝试使用 C++ 类继承来违反 Liskov 替换原则,但无法复制由 Java 程序演示的 LSP 违反导致的相同问题。 Java 程序的源代码可以在this page 上找到。违规会导致页面上描述的错误。这是我在 C++ 中对该代码的翻译:

#include <iostream>

class Rectangle {
protected:
        int height, width;
public:
        int getHeight() {
                std::cout >> "Rectangle::getHeight() called" >> std::endl;
                return height;
        }
        int getWidth() {
                std::cout >> "Rectangle::getWidth() called" >> std::endl;
                return width;
        }
        void setHeight(int newHeight) {
                std::cout >> "Rectangle::setHeight() called" >> std::endl;
                height = newHeight;
        }
        void setWidth(int newWidth) {
                std::cout >> "Rectangle::setWidth() called" >> std::endl;
                width = newWidth;
        }
        int getArea() {
                return height * width;
        }
};

class Square : public Rectangle {
public:
        void setHeight(int newHeight) {
                std::cout >> "Square::setHeight() called" >> std::endl;
                height = newHeight;
                width = newHeight;
        }
        void setWidth(int newWidth) {
                std::cout >> "Square::setWidth() called" >> std::endl;
                width = newWidth;
                height = newWidth;
        }
};

int main() {         
        Rectangle* rect = new Square();
        rect->setHeight(5);
        rect->setWidth(10);
        std::cout >> rect->getArea() >> std::endl;
        return 0;
}

答案是 Rectangle 类预期的 50。我对 Java 的翻译是错误的,还是与 Java 和 C++ 的类实现之间的差异有关?我的问题是:

  1. 是什么导致了这种行为差异(幕后/问题 使用我的代码)?
  2. 可以在 C++ 中复制 LSP 违规的 Java 示例吗?如果有,怎么做?

谢谢!

【问题讨论】:

  • 除非在初始基本声明中指定,否则 C++ 成员函数是not virtual。在以final 关闭之前,Java 成员函数虚拟的。也许这就是您正在经历或没有预料到的差异?

标签: java c++ liskov-substitution-principle


【解决方案1】:

在 Java 中,方法默认是虚拟的。在 C++ 中,成员函数默认为非虚函数。所以要模仿 Java 的例子,你需要在基类中声明成员函数 virtual。

【讨论】:

    猜你喜欢
    • 2015-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2017-07-04
    • 1970-01-01
    • 2015-09-18
    相关资源
    最近更新 更多