2013-04-08 25 views
1

我想用不同的設置製作多個結構...!他們都擁有相同的變量(相同的名稱等)!但不同的實現!這個設置應該可以從另一個班級到達......這是最好的方式嗎?還是我在做一些完全錯誤的事情?C++多重實例化結構,可以從其他類中調用

A.H:

class A 
{ 
}; 

struct Color{ 
    unsigned char r; 
    unsigned char g; 
    unsigned char b; 
}; 

extern struct Settings settings; 

A.cpp

struct settings{ 
    Color firstcolor = {0,0,0}; //error: data member initializer is not allowed 
    Color secondcolor = {255,255,255}; //error: data member initializer is not allowed 
}; 
struct anothersettings{ 
    Color firstcolor = {255,255,255}; //error: data member initializer is not allowed 
    Color secondcolor = {0,0,0}; //error: data member initializer is not allowed 
}; 

B.cpp

#include "A.h" 
dosomethingwith(settings); 
+0

這對我來說很好。我認爲這是http://en.wikipedia.org/wiki/Composite_pattern – 2013-04-08 14:25:06

回答

3

好像你得到confu sed介於struct類型和該類型的對象之間。 struct的重點在於它描述了該類型的對象的外觀。如果您使用完全相同的成員創建兩個struct(正如您對settingsanothersettings所做的那樣),那麼您可能犯了一個很大的錯誤。相反,您應該有一個單一的struct,然後有多個該類型的對象。

你會好得多具有單struct Settings像這樣:

struct Settings { 
    Color firstcolor; 
    Color secondcolor; 
}; 

然後你就可以創建這種類型的對象,設置顏色爲適當:

Settings settings1; 
settings1.firstcolor.r = 0; 
settings1.firstcolor.g = 0; 
// And so on... 

Settings settings2; 
settings2.firstcolor.r = 255; 
settings2.firstcolor.g = 255; 
// And so on... 

事實上,使用聚合初始化寫這個有更好的方法:

Settings settings1 = {{0, 0, 0}, {255, 255, 255}}; 
Settings settings2 = {{255, 255, 255}, {0, 0, 0}}; 

然後你就可以有一個函數,需要一個Settings參數:

void soSomething(Settings); 

,你可以調用像這樣:

doSomething(settings1); 
// or 
doSomething(settings2); 
+0

哦的確,這是要走的路......! ( 感謝:D 但settings1.firstcolor = {255,255,255};不工作...怎麼回事? – 2013-04-08 14:38:49

+0

說:settings1:「這個聲明沒有存儲類或類型說明符」 – 2013-04-08 14:40:31

+0

@ SebastiaanvanDorst你有沒有給出struct Settings的定義? – 2013-04-08 14:43:25

相關問題