2013-07-22 80 views
0

對於以下基類派生和列表類,如何使用非默認構造函數base(int newsize)而不是默認構造函數base()來初始化每個元素,以便我立即爲列表中的每個元素創建一個正確的數組大小?從派生類數組中初始化基類非默認構造函數

class base 
{ 

    // default constructor 
    base(); 

    // constructor to a newsize 
    base(int newsize); 


    int *array; 
    int size; 
}; 

class derive : public base 
{ 

    int somethingelse; 
}; 

class list 
{ 

    // constructor to newlistsize element with newarraysize array 
    list(int newlistsize, int newarraySize); 

    derive *element; 
    int listSize; 
}; 


list::list(int newlistsize, int newarraySize) 
{ 

    element = new derive [newlistsize]; 
// how to initialize the array with newarraysize 

} 

回答

0

您需要使用初始化列表。

class derive : public base 
{ 
    public: 
     derive(int size):base(size) 
        // ^^^^^^^^^ invoking base class parameterized constructor 
     {} 
    ..... 
  1. 類成員默認都是私有的。你需要有基本的公共訪問說明符並派生構造函數才能工作。
  2. 不要自己管理記憶。改用智能指針。在這種情況下,您不必擔心釋放資源。
  3. What is rule of three ?
+0

請注意,基礎構造函數是私有的。 OP可能只是提供一個簡短的代碼示例,並忘記它。但是,如果沒有,警告他。 – Manu343726

相關問題