2012-08-04 133 views
1

我想弄清楚如何在构造函数的初始化列表中声明任意大小的数组。如果这是不可能的,我应该怎么做呢?在构造函数的初始化列表中的数组

例如:

class vectorOfInt 
{ 
public: 

private: 
    int _size; 
    int _vector[]; 
}; 

vectorOfInt::vectorOfInt() 
    :_size(32), 
    _vector(size) 
{ 
} 

基本上,我想阵列_Vector至(在这种情况下32)被初始化为大小。我怎么做?感谢您的任何意见。

回答

4

使用std::vector

#include <vector> 

class vectorOfInt 
{ 
public: 

private: 
    int _size; // probably you want to remove this, use _vector.size() instead. 
    std::vector<int> _vector; 
}; 

vectorOfInt::vectorOfInt() 
    :_size(32), 
    _vector(size) 
{ 
} 

编辑:既然你不希望使用std::vector,你必须自己处理内存。如果在编译时知道数组的大小,可以使用内置数组,但我怀疑是这种情况。你必须这样做:

#include <memory> 

class vectorOfInt 
{ 
public: 

private: 
    int _size; 
    // If C++11 is not an option, use a raw pointer. 
    std::unique_ptr<int[]> _vector; 
}; 

vectorOfInt::vectorOfInt() 
    :_size(32), 
    _vector(new int[size]) 
{ 
} 
+0

,避免前导下划线(我知道这是不是你的主意) – juanchopanza 2012-08-04 22:06:51

+0

的练习的要点是重新创建向量类的方式,它的工作只是为INT – 2012-08-04 22:07:16

+0

是领先的下划线不良作风?是否有任何其他公约来识别私人数据字段和方法? – 2012-08-04 22:08:25

1

你想要的是使用一个向量,然后使用'reserve'关键字。这将为32个元素分配空间,并且可以将它们初始化为任何你想要的。

#include<vector> 
using namespace std; 

class vectorOfInt 
{ 
public: 

private: 
     int _size; 
     vector<int> _vector; 

vectorOfInt() 
{ 
    _size = 32; 
    _vector.reserve(32); 

} 



}; 
+0

我不认为'resize'是这里需要的。我们仍然需要push_back,并把它看作是零大小(它会是)。 – juanchopanza 2012-08-04 22:21:16

+0

这不是调整大小。这是'储备'。分配空间后,您可以对这32个元素进行push_back。 – Nathan822 2012-08-04 22:21:55

+0

对不起,我的意思是“保留”。 'resize'会很好,但是你不妨使用size构造函数。 – juanchopanza 2012-08-04 22:23:21

相关问题