为什么在此C++片段中未显示利斯科夫替代原则违规
Why are Liskov Substitution Principle violations not shown in this C++ snippet?
我正在尝试使用类继承来违反Liskov替换原则C++但无法复制由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;
}
答案是 50,正如矩形类所期望的那样。我的Java翻译是错误的,还是与Java和C++类实现之间的差异有关?我的问题是:
- 是什么导致了这种行为差异(引擎盖下/问题)用我的代码)?
- 是否可以在 C++ 中复制 LSP 违规的 Java 示例?如果是这样,如何?
谢谢!
在Java中,默认情况下方法是虚拟的。在C++中,成员函数默认为非虚拟函数。因此,为了模拟 Java 示例,您需要在基类中声明成员函数 virtual。
相关文章:
- С++ wxWidgets:代码架构,设计原则和模式
- 我需要如何更改我的程序以使用打开/关闭原则?
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- Visual Studio 2017扩展选项卡中的C++核心指导原则检查器丢失
- 是否有一种设计模式或面向对象的基本原则来处理这种共享资源的情况?
- 分层状态机涉及哪些原则,以及如何实现基本模型?
- 如何应用注册表模式使"select class depend on input"遵守开放封闭原则?
- 不兼容的操作原则到三元op
- 代码在Visual C ++中无法按预期工作(来自bjarne stroustrup编程和原则书籍2n版本的示例)
- 用坚实的原则用 arduino 写作
- 提升月份的行为的原则是什么?
- C++中的依赖反转(来自 S.O.L.I.D 原则)
- Objective-C 块文字语法原则
- BST 与 C++ 年的 OOP 原则
- 何时违反单一责任原则
- 类实例和指针背后的Delphi设计原则是什么
- 原则上不可能C++进行严格的模板评估
- 如果违反了利斯科夫替代原则,我该怎么办?
- 使用"cin"进行演练 #7 获得不同的结果 编程:使用C++的原则和实践 (Stroustrup) 第 4 章
- 标准::比率背后的设计原则<>