[英]C++ initialize all values of a member array for a class
在C ++中如何初始化類的成員數組的所有值?
#define MAX_MATRIX 20
Class Matrix {
public:
Matrix(); //constructor
protected:
int n[MAX_MATRIX]; // note cannot do = { 0} or w/e here
};
Matrix::Matrix()
{
// how to set all n to -1?
}
這是C ++ 03的一個明顯缺點。 在C ++ 11中,這已得到修復,您現在可以初始化所有內容,包括數組:
class Matrix
{
public:
Matrix() : n { } { }
protected:
static const unsigned int MAX_MATRIX = 20;
int n[MAX_MATRIX];
};
(在C ++中也不需要令人討厭的預處理器宏。)
在C ++ 03中,您根本無法初始化數組成員,但您可以在構造函數體中將其設置為有意義的內容,例如通過std::fill(n, n + MAX_MATRIX, 0);
。
(當然,說std::array<int, MAX_MATRIX> n;
.會更好。)
這有一種類型:
class Matrix {
public:
Matrix() : n() { n.fill(-1); }
protected:
std::array<int, 20> n;
};
for (unsigned i = 0; i < MAX_MATRIX; ++i) n[i] = -1;
#include <cstring>
...
Matrix::Matrix()
{
static bool init=false;
static int n_init[MAX_MATRIX];
if (!init){
for(int i=0; i<MAX_MATRIX; i++){
n_init[i] = -1;
}
init = true;
}
memcpy(n,n_init,MAX_MATRIX*sizeof(int));
}
數組n_init
被初始化一次並存儲在內存中,然后所有后續構造都是一個沒有循環的快速內存副本。 如果增加MAX_MATRIX
的大小, MAX_MATRIX
像循環索引那樣增加速度,特別是如果你多次調用Matrix::Matrix()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.