2015-08-25 123 views
0

我已經在這個網站上看過很多類似的問題,但沒有回答我想要做的事情。C++中操作符的繼承關係

public class base { 
public: 
    base(){ 
     //Default Constructor 
    } 

    base(int num){ 
     // use num to create base 
    } 

    base& operator=(base&& _data){ 
     // do move assignment stuff 
    } 
}; 

public class derived : public base { 
public: 
    derived() : base() { 
     int num1; 
     //Do some stuff 

     // Now I want to assign the base of this class with a new base 
     base::operator=(Base(num1)); 
    } 
}; 

我想在派生類的構造過程中調用基類的移動賦值(或只是定期賦值)。通過這種方式,派生類可以在創建基礎之前解析一些信息。這似乎並不奏效。有人有主意嗎?

+2

定義「似乎並沒有工作。」另外,你爲什麼要做這樣的事情?只需用正確的編號直接構建'base'即可。 – Barry

+0

@Barry:從它的外觀來看,當'base'構造函數被調用時,這個數字可能還不知道,所以它不能在構造函數參數中傳遞。 –

+0

我假設'Base(num1)'你的意思是'base(num1)'? –

回答

1

請記住,基類在初始化之前構造函數體被輸入。因此,用你的方法,你首先初始化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()) { } 
};