初始化嵌套结构数组

时间:2016-05-03 16:14:03

标签: c++ arrays structure

我正在尝试初始化这个嵌套的结构数组,我的编译器一直告诉我,我有太多的初始化值。还有另外一种方法可以解决这个问题吗?或者有人能告诉我我做错了什么。

#include<iostream>
#include<iomanip>
#include<string>
using namespace std;

const int NUM_BOOKS = 3;

struct BookInfo
{
   string title;
   double price;
};

struct Author
{
    string name;
    BookInfo books[NUM_BOOKS];
};

//Prototype
void showInfo(Author a[], int);


int main()
{
   Author a[] =
  {
    { "NONE", { "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 } },
    { "NONE", { "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 } },

    { "NONE", { "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 } }
 };

cout << fixed << showpoint << setprecision(2);
showInfo(a, NUM_BOOKS);

return 0;
}

//This fucnction displays the array
void showInfo(Author a[], int size)
{
    for (int i = 0; i< size; i++)
{
    cout << "The author: " << a[i].name << endl;
    for (int j = 0; j < size; j++)
    {
        cout << "\t The title: " << a[i].books[j].title << ", ";
        cout << "\t The price: " << a[i].books[j].price << endl;
    }

}

cout << endl;

}

1 个答案:

答案 0 :(得分:4)

数组也是对象,因此您必须使用{}来对其进行边框处理:

Author a[] =
{
 { "NONE", {{ "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 }} },
 { "NONE", {{ "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 }} },
 { "NONE", {{ "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 }} }
};