0
我嘗試用C++類繼承違反了里氏替換原則,但無法複製從LSP違規用Java程序演示導致同樣的問題。 Java程序的來源可以在this page上找到。違規會導致頁面上描述的錯誤。這是我在C++中對該代碼的翻譯:爲什麼在此C++代碼片段中沒有顯示Liskov替換原則違規?
#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 **](http://en.wikipedia.org/wiki/Virtual_function)。直到以final結尾,Java成員函數*都是虛擬的。也許這就是你正在經歷的或者其他方面的差異 - 沒有預料到的? – WhozCraig 2014-11-23 08:39:06