簡體   English   中英

我可以在結構中放一個列表嗎?

[英]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)中也不是這種情況, structclass在C ++中實際上是相同的,唯一的區別是成員方法和變量的默認可見性,正如其他答案所指出的那樣。

但是,您不能將非PODS對象放入聯合。

我建議你使用std::vectorstd::array而不是C風格的數組。 如果你的數組應該是動態大小的話, std::vector可能是最有用的。 如果你使用普通的new或甚至malloc() ,你的對象將不會被自動釋放(甚至沒有用malloc()初始化)

是的,沒有理由不這樣做。 C ++中structclass之間的唯一區別是

A) struct成員默認是公共的,並且

B) struct繼承默認是公共的(即struct A : B等同於class A : public B ,其中Bclass 。)

只要對象具有或支持默認構造函數,在結構內使用列表或任何對象是完全可以接受的。

默認構造函數是必需的,因為首次聲明struct變量時,它也會被初始化。 其中的任何對象也將通過調用默認構造函數進行初始化。

在C ++中將類的實例作為結構的成員沒有任何問題,除非您依賴於C ++將結構的實例視為POD(普通舊數據)對象。 (與逐位復制等一樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM