請記住,基類在初始化之前構造函數體被輸入。因此,用你的方法,你首先初始化base
,然後通過賦值覆蓋它。這不好。
使用委託構造和私人助手功能:
class derived : public base {
private:
static int help() { /* Do some stuff */ }
// private constructor to be called with the helper values
derived (int i) : base (i) { }
public:
derived() : derived (help()) { }
};
當然,在這種情況下,你可以只通過
derived() : base (help()) { }
定義構造函數然而上述委託構造方法變得有用如果必須爲基類構造函數計算多個參數值:
class base {
public:
base (int i, double d);
};
class derived : public base {
private:
struct BaseParams { int i; double d; };
static BaseParams help() {
BaseParams p;
/* Do some stuff and set p.i and p.d */;
return p;
}
// private constructor to be called with the helper values
derived (BaseParams const & p) : base (p.i, p.d) { }
public:
derived() : derived (help()) { }
};
如果你真的想構建一個base
對象和移動它,使用基地的轉移構造函數:
class base {
public:
base (int i, double d);
base (base &&);
};
class derived : public base {
private:
static base help() {
/* Do some stuff and finally construct a base object */;
return base { /* calculated parameters for constructor of base */ };
}
// private constructor to be called with a base object to move from
derived (base && b) : base (std::move (b)) { }
public:
derived() : derived (help()) { }
// or simply derived() : base (help()) { }
};
定義「似乎並沒有工作。」另外,你爲什麼要做這樣的事情?只需用正確的編號直接構建'base'即可。 – Barry
@Barry:從它的外觀來看,當'base'構造函數被調用時,這個數字可能還不知道,所以它不能在構造函數參數中傳遞。 –
我假設'Base(num1)'你的意思是'base(num1)'? –