2013-07-22 78 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

相关问题