由于我们的产品有多种颜色,我正在尝试将列表用作结构的一部分。这是我可以做的事情还是我应该只使用数组?无论哪种方式,我都没有在网上找到任何示例。
#include "stdafx.h"
#include<iostream>
#include<string>
#include<sstream>
#include<cctype>
#include<list>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////
// Constances
////////////////////////////////////////////////////////////////////////////////////////
#define N_PRODUCT 3
struct Brand_t {
int Model_Num;
string Product_Name;
list<string> Colors;
} brands [N_COLOR];
////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////
int main()
{
string mystr;
int n;
for (n=0; n < N_PRODUCT; n++)
{
cout << "Enter Model Number: ";
std::getline (cin,mystr);
stringstream(mystr) >> brands[n].model_Num,4;
cout << "Enter Product Name: ";
getline(cin,classrooms[n].Product_Name);
list<string>::iterator it;
Students.push_back ("Red");
Students.push_back ("Yellow");
Students.push_back ("Blue");
}
return 0;
}
最佳答案
是的,这是可以做到的。多亏了 RAII,list
对象将根据结构的生命周期自动初始化和释放。请注意,即使在其他编程语言(如 Object Pascal)中情况并非如此,struct
和 class
在 C++ 中实际上是相同的,唯一的区别是默认值正如其他答案所指出的那样,成员方法和变量的可见性。
你不能放非PODS对象变成 union 体。
我建议您使用 std::vector
或 std::array
而不是 C 风格的数组。如果您的数组应该具有动态大小,则 std::vector
可能最有用。如果您使用普通 new
甚至 malloc()
,那么您的对象将不会自动释放(甚至不会使用 malloc()
初始化)
关于c++ - 我可以将列表放入结构中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319383/