簡體   English   中英

C ++初始化類的成員數組的所有值

[英]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?
}

你可以使用std::fill

std::fill(begin(n), end(n), -1);

(這些beginend函數可以在C ++ 11中的命名空間std中找到,或者您可以在C ++ 03中自己輕松實現它們

這是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM