我正在尝试使用 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++ 的类实现之间的差异有关?我的问题是:
- 是什么导致了这种行为差异(在我的代码的幕后/问题下)?
- 可以在 C++ 中复制 LSP 违规的 Java 示例吗?如果是这样,怎么做?
谢谢!