首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ protected 繼承導致基類成員不可直接訪問的構造函數調用缺失問題

     編輯:程式設計綜合問答

錯誤現象

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;
}

關鍵點

  1. protected 繼承:基類 public/protected → 派生類 protected,外部不可訪問
  2. 構造函數不自動鏈式:派生類構造函數必須在初始化列表顯式調用基類構造
  3. volume() 依賴基類數據:必須確保基類成員已初始化
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved