我有一個關於如何使用初始化項列表來構造繼承自基類的構造函數的派生類的構造函數的問題。使用具有繼承性的構造函數庫和成員初始值設定項列表
這是工作的代碼:
class base {
public:
base():x(0) {}
base(int a):x(a) {}
private:
int x;
};
class derived : public base {
public:
derived():base():y(0) { y=0; }
derived(int a, int b):base(a) { y=b; }
private:
int y;
};
不過,我想使用成員初始化列表直接初始化變量,而這將導致一個錯誤:
class base {
public:
base():x(0) {}
base(int a):x(a) {}
private:
int x;
};
class derived : public base {
public:
//derived():base():y(0) {} //wrong
//derived(int a, int b):base(a):y(b) {} //wrong
derived():base(), y(0) {} // corrected
derived(int a, int b): base(a), y(b) {} //corrected
private:
int y;
};
有什麼從另一個構造函數繼承來使用初始化列表的構造函數的正確語法?
謝謝:)
請修復語法:'derived():base():y(0){}' - >'derived():base(), y(0){}'(您需要一個逗號) – 2015-01-04 14:05:51
謝謝,這回答了我的問題 – pkdc 2015-01-04 14:08:56
嘗試正確地讀取編譯器錯誤... – Ankur 2015-01-04 14:13:29