0

我正在尝试使用 C++ 类继承来违反 Liskov 替换原则,但无法复制由 Java 程序演示的 LSP 违规导致的相同问题。Java 程序的源代码可以在这个页面上找到。违规会导致页面上描述的错误。这是我在 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 示例吗?如果是这样,怎么做?

谢谢!

4

1 回答 1

1

在 Java 中,方法默认是虚拟的。在 C++ 中,成员函数默认为非虚函数。因此,为了模仿 Java 示例,您需要在基类中声明成员函数 virtual。

于 2014-11-23T10:05:35.893 回答