如何在C ++中初始化struct数组?

时间:2011-12-16 13:00:37

标签: c++ arrays struct initialization

我的C ++代码中有以下struct(我使用的是Visual Studio 2010):

struct mydata
{
    string scientist;
    double value;
};

我想做的是能够快速初始化它们,类似于C99中的数组初始化或C#中的类初始化,ála

mydata data[] = { { scientist = "Archimedes", value = 2.12 }, 
                  { scientist = "Vitruvius", value = 4.49 } } ;

如果在C ++中对于结构数组不可能这样做,我可以为一个对象数组做吗?换句话说,数组的基础数据类型并不重要,重要的是我有一个数组,而不是一个列表,并且我可以用这种方式编写初始化器。

3 个答案:

答案 0 :(得分:52)

C ++中的语法几乎完全相同(只是省略了命名参数):

mydata data[] = { { "Archimedes", 2.12 }, 
                  { "Vitruvius", 4.49 } } ;

在C ++ 03中,只要数组类型为aggregate,这就有效。在C ++ 11中,这适用于任何具有适当构造函数的对象。

答案 1 :(得分:0)

根据我的经验,我们必须设置 data 的数组大小,并且它必须至少与实际的初始化列表一样大:

//          ↓
mydata data[2] = { { "Archimedes", 2.12 }, 
                  { "Vitruvius", 4.49 } } ;

答案 2 :(得分:0)

下面的程序执行结构变量的初始化。它创建了一个结构指针数组。

struct stud {
    int id;
    string name;
    stud(int id,string name) {
        this->id = id;
        this->name = name;
    }
    void getDetails() {
        cout << this->id<<endl;
        cout << this->name << endl;
    }
};

 int main() {
    stud *s[2];
    int id;
    string name;
    for (int i = 0; i < 2; i++) {
        cout << "enter id" << endl;
        cin >> id;
        cout << "enter name" << endl;
        cin >> name;
        s[i] = new stud(id, name);
        s[i]->getDetails();
    }
    cin.get();
    return 0;
}