如何在C++中初始化结构体数组?

48

我在我的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++中结构体数组不支持这种操作,那么我能否对对象数组进行操作呢?换句话说,一个数组的底层数据类型并不重要,重要的是我需要一个数组而不是列表,并且我可以以这种方式编写初始化程序。


1
没有理由它不能工作...(顺便说一句,那应该是.scientist = ...)你试过了吗? - fge
@fge 是的,它被称为聚合初始化,并在此处进一步详细解释:[http://en.cppreference.com/w/cpp/language/aggregate_initialization]。 - pfabri
3个回答

70

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

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

在C++03中,只要数组类型是一个聚合体,这就有效。在C++11中,只要对象有一个适当的构造函数就可以了。


2
我认为“统一初始化”通常指的是“列表初始化”形式(即没有=)?我在标准中找不到有关统一初始化的参考。 - CB Bailey
@BjörnPollex 我认为重新提及这件事情不会是一件坏事。 - cjcurrie
这似乎是gcc的扩展功能。据我所知,它不是标准的C++语法,也不太可能在其他编译器中运行。无论如何,在Visual Studio中它是不起作用的。 - undefined

0
根据我的经验,我们必须设置data数组的大小,并且它至少要和实际的初始化列表一样大:
//          ↓
mydata data[2] = { { "Archimedes", 2.12 }, 
                  { "Vitruvius", 4.49 } } ;


-3
以下程序执行结构变量的初始化。它创建了一个结构指针数组。
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接