这是这组的最后一题。我需要创建一个动态分配的结构数组,然后我必须访问这些结构中的数据以插入到输出流中。问题是,我使用的编译器 (g++) 不接受我为数组中的结构赋值的方式。这是代码:
#include <iostream>
#include <cstring>
using namespace std;
struct candy
{
string name;
float weight;
int cal;
};
int main()
{
candy * pc = new candy [3];
pc[0] = {"ChocoBar", 4.5, 230};
pc[1] = {"SugarCrack", 9.3, 690};
pc[2] = {"TamponBar", 1.3, 100};
cout << "Bar None:\n";
cout << "Name: " << pc[0].name << endl;
cout << "Weight: " << pc[0].weight << endl;
cout << "Calories: " << pc[0].cal << "\n\n";
cout << "Bar One:\n";
cout << "Name: " << pc[1].name << endl;
cout << "Weight: " << pc[1].weight << endl;
cout << "Calories: " << pc[1].cal << "\n\n";
cout << "Bar Two:\n";
cout << "Name: " << pc[2].name << endl;
cout << "Weight: " << pc[2].weight << endl;
cout << "Calories: " << pc[2].cal << "\n\n";
delete [] pc;
return 0;
}
定义了结构类型——糖果;并创建了一个指针 (pc) 来保存由 new 分配给三个结构的内存地址,然后我尝试为这三个结构赋值。然而,编译器吐出一条消息说“扩展初始化列表不可用......”,这告诉我我搞砸了代码,编译器甚至不将我的结构类型识别为结构(否则它会接受我的三个值列表)。
我今天刚学了数组、结构体、指针和变量的动态分配,当涉及到静态分配的结构体数组和动态分配的结构体和数组(分别)时,我第一次尝试就完成了练习;但是动态分配的结构数组让我很伤心。
请帮忙。
最佳答案
首先,您需要包含 <string>
std::string
的 header .其次,您需要确保您的编译器支持 C++11。这将使以下代码合法:
#include <iostream>
#include <string> // for std::string
struct candy
{
std::string name;
float weight;
int cal;
};
int main()
{
candy* pc = new candy[3];
pc[0] = {"ChocoBar", 4.5, 230}; // requires C++11
delete [] pc;
}
接下来可以了解 std::vector
,一个为您进行动态内存分配/取消分配并可以调整其存储大小的类模板,有效地充当一个可以增加大小的数组:
#include <iostream>
#include <string>
#include <vector>
struct candy
{
std::string name;
float weight;
int cal;
};
int main()
{
using std::cout;
using std::endl;
using std::vector;
vector<candy> pc;
pc.push_back({"ChocoBar", 4.5, 230});
pc.push_back({"SugarCrack", 9.3, 690});
for (size_t i = 0; i < pc.size(); ++i)
{
cout << "Name: " << pc[i].name << endl;
}
}
请注意,在 C++11 中,您还可以使用一组元素初始化 vector :
std::vector<candy> candies{{"ChocoBar", 4.5, 230},
{"SugarCrack", 9.3, 690},
{"TamponBar", 1.3, 100}};
关于c++ - 动态分配的结构数组 : Assignment Issues (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131951/