Box 繼承 Rectangle,調用 b.volume() 返回錯誤值,因 length/width 未初始化。
Box 未調用基類的 setlength()/getlength() 等方法初始化 length/width。protected 繼承下,基類 public 成員變為 protected,派生類可訪問,但構造函數不自動鏈式調用(除非显式調用)。
class Box : protected Rectangle {
// ...
double volume() {
// 方案 1:在 volume 內初始化
setlength(); getlength();
setwidth(); getwidth();
return (length * width) * height;
}
// 方案 2:構造函數鏈式調用 (需基類有參構造)
Box(double l, double w, double h) : Rectangle(l, w) { // 假設 Rectangle 有構造
height = h;
}
};
#include
#include
using namespace std;
class Rectangle {
protected:
double length, width;
public:
void setLength(double l) { length = l; }
void setWidth(double w) { width = w; }
double getLength() const { return length; }
double getWidth() const { return width; }
};
class Box : protected Rectangle {
double height;
public:
void setHeight(double h) { height = h; }
double volume() {
// 必須先設置 length/width
// 這裡演示交互式輸入,實際應從參數/配置獲取
double l, w;
cout << "Length: "; cin >> l; setLength(l);
cout << "Width: "; cin >> w; setWidth(w);
return length * width * height;
}
};
int main() {
Box b;
b.setHeight(5);
cout << "Volume: " << b.volume() << endl;
return 0;
}