[英]Can I put a list in a struct?
我試圖使用列表作為結構的一部分,因為我們的產品有多種顏色。 這是我可以做的一些事情,還是我應該使用數組? 無論哪種方式,我都沒有在網上找到任何例子。
#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對象放入聯合。
我建議你使用std::vector
或std::array
而不是C風格的數組。 如果你的數組應該是動態大小的話, std::vector
可能是最有用的。 如果你使用普通的new
或甚至malloc()
,你的對象將不會被自動釋放(甚至沒有用malloc()
初始化)
是的,沒有理由不這樣做。 C ++中struct
和class
之間的唯一區別是
A) struct
成員默認是公共的,並且
B) struct
繼承默認是公共的(即struct A : B
等同於class A : public B
,其中B
是class
。)
只要對象具有或支持默認構造函數,在結構內使用列表或任何對象是完全可以接受的。
默認構造函數是必需的,因為首次聲明struct變量時,它也會被初始化。 其中的任何對象也將通過調用默認構造函數進行初始化。
在C ++中將類的實例作為結構的成員沒有任何問題,除非您依賴於C ++將結構的實例視為POD(普通舊數據)對象。 (與逐位復制等一樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.