#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming = {{1,"ONE"},{2,"TWO"}};
cout<<naming.numline<<":"<<naming.numname<<std::endl;
return 0;
}
发生此错误:
main.cpp:10:33: error: braces around scalar initializer for type int
} naming = {{1,"ONE"},{2,"TWO"}};
答案 0 :(得分:1)
由于您要存储两个值,因此必须创建一个结构类型的数组。
#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming[] = {{1,"ONE"},{2,"TWO"}};
cout<<naming[0].numline<<":"<<naming[0].numname<<std::endl;
cout<<naming[1].numline<<":"<<naming[1].numname<<std::endl;
return 0;
}
答案 1 :(得分:1)
你有
struct naming { … } naming = …
表示您正在创建单个naming
对象。但是你的初始化器
{{1,"ONE"},{2,"TWO"}}
与该意图不符。
看起来您正在尝试初始化naming
个对象的集合。如果是这种情况,您应该将其设为std::vector<naming>
而不是单个对象:
struct naming { … }; // definition of naming
std::vector<naming> namings = {{1, "ONE"}, {2, "TWO"}}; // collection of objects
然后您可以访问各个命名对象,如下所示:
// access the first element:
std::cout << namings.at(0).numline << ":" << namings.at(0).numname << std::endl;
// access the second element:
std::cout << namings.at(1).numline << ":" << namings.at(1).numname << std::endl;