簡體   English   中英

在C ++中,當我想在初始化類對象數組時通過構造函數初始化類成員時,我該怎么辦?

[英]In C++, What should I do when I want to initialize class members via constructor when I initialize a class object array?

我以為我可以做到以下幾點:

#include <iostream>

using namespace std;

class cl
{
  public:
    double* Arr;
    cl(int);
};

cl::cl(int i)
{
    Arr=new double[i];
    Arr[0]=11;
};

int main()
{
    cl* BB;
    BB=new cl(3)[3];      /* I want to initialize a class member Arr for each element of the class cl array BB when I initialize this array by means of constructor. What should I do? */
    cout << cl[1].Arr[0] << endl;                                                                                                   

    return 0;
}

但是很明顯,我注意到的那一行是有問題的。 編譯器無法編譯。

在C ++ 11中,您可以使用大括號初始化器:

cl* BB = new cl[3] {1, 2, 3};

或者更詳細,所以很明顯這些數字作為參數傳遞給不同對象的構造函數:

cl* BB = new cl[3] {{1}, {2}, {3}}; 

雖然你無論如何動態分配內存,但最好使用std::vector ,如果你想用相同的參數初始化大量的對象,它也會更方便:

std::vector<cl> BB(300, 3);

但是,如果cl沒有副本構造函數,則不會編譯std::vector初始化。 在這種情況下,您可以使用emplace_back()

vector<cl> BB;
BB.reserve(300);
for(int i = 0; i < 300; ++i)
    BB.emplace_back(3);

這反過來可以包裝到模板back_emplacer_iterator以與std::fill_n一起使用

有幾種方法:

  • C ++ 11 初始化列表

     cl* BB = new cl[3] {42, 42, 42}; 
  • STL-vector(推薦)

     std::vector<cl> BB( 3, cl( 42 ) ); 

作為C ++ 11之前的版本,還有其他涉及更多的解決方案,它們依賴於放置新運算符,盡管我不建議這樣做。

new表達式的格式是一種類型,后跟一個初始化程序。 如果要分配3個cl對象的數組,則類型為cl[3] 你不能說cl(3)[n]因為cl(3)不是一個類型。

在C ++ 03中,動態分配數組的唯一有效初始值設定項是() ,它對每個元素進行值初始化,但由於您的類型沒有默認構造函數,所以不能這樣做。

在C ++ 11中,您可以使用初始化列表將參數傳遞給每個數組元素:

cl* ptr = new cl[3]{ 3, 3, 3};

數組中的每個元素都將由默認構造函數(無參數構造函數)初始化。 之后,您可以調用執行所需任務的任何函數。 更正的程序示例:

class cl
{
  public:
    double* Arr;
    cl(int i = 0);
    ~cl();
    void allocArr(int i=0);
};

cl::cl(int i)
{
    allocArr(i);
}

void cl::allocArr(int i)
{
    if (i <= 0) {
        Arr = (double *) NULL;
    }
    else {
        Arr=new double[i];
        Arr[0]=11;
    }
};

cl::~cl() {
    if (Arr)
      delete [] Arr;
}

int main()
{
    cl* BB;
    BB=new cl[3]; // default constructor 
    for (int i = 0; i < 3; i++) {
        BB[i].allocArr(3);
    }

    cout << BB[1].Arr[0] << endl;                                                                                                   

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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