【发布时间】: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++ 的类实现之间的差异有关?我的问题是:
- 是什么导致了这种行为差异(幕后/问题 使用我的代码)?
- 可以在 C++ 中复制 LSP 违规的 Java 示例吗?如果有,怎么做?
谢谢!
【问题讨论】:
-
除非在初始基本声明中指定,否则 C++ 成员函数是not virtual。在以
final关闭之前,Java 成员函数是虚拟的。也许这就是您正在经历或没有预料到的差异?
标签: java c++ liskov-substitution-principle