2014-10-19 59 views
1

即時通訊新手,所以我希望你能幫助我。我可以在其他班級內創建班級嗎?並呼籲所有在一起

我有這個班出場,我展示了一下CPP

Appearances::Appearances(const char* id, float shininess,const char* textureref) 
{this->id = id; 
setShininess(shininess); 
this->textureref = textureref; 
} 

的代碼,我想加入其他類「組件」像這樣

Component(float ambient[4] , float diffuse[4] , float specular[4]) 
    {setAmbient(ambient); 
    setDiffuse(diffuse); 
    setSpecular(specular); 
    } 

而且我想要什麼是,我可以打電話出場與這一切加入,例如:

app = new Appearances(idAppearance, vAmb, vDif, vSpec, shininess, txtRef); 

IM試圖讓這個在C + +

<appearance id="app1" shininess="6.0" textureref="ss" > 
      <component type="ambient" value="5 5 5 5" /> 
      <component type="diffuse" value="5 5 5 5" /> 
      <component type="specular" value="0.6 0.6 0.6 0.6" /> 
    </appearance> 

我不知道我是否很好地解釋了我想要的,但有人能幫助我嗎? :)

回答

0

爲此,您需要更改構造函數以包含組件類的數據。

Appearances::Appearances(const char* id,float ambient[4] , float diffuse[4] , float specular[4], float shininess,const char* textureref) 

然後在構造函數中調用Component的構造函數。

但是這提出了設計問題。如果你可以初始化你的組件,它意味着它只是一個你想要做的邏輯組,我建議使用命名而不是像comp_Ambient。

如果你想在你的類中有多個組件,那麼你不想在構造函數中初始化它。

我看到使用這種設計的另一個原因是能夠在其他對象上使用組件,那麼不要把它放在類中。

+0

我編輯了我的問題,最後我展示了我需要做的事 – terrorista 2014-10-19 11:09:34

+0

你的組件只能是float [4]嗎? – 2014-10-19 12:15:30

+0

是的,3浮動[4],環境漫反射和鏡面 – terrorista 2014-10-19 12:51:19

0

您是否需要完全訪問組件成員和功能?如果是這樣,我看到你的問題有兩個可能的答案。最簡單的方法是創建一個繼承於外觀和組件的派生類。例如,您可以聲明class Design: public Appearances, public Component。雖然多重繼承有時會使設計複雜化,但它似乎是最直接的選擇。查看更多here

如果您想將功能添加到現有的Appearances類,可以通過將Component設置爲外觀的朋友類來完成此操作。這是通過將friend class Appearances;行添加到組件類來完成的,該類允許外觀訪問組件的所有成員。在這種情況下,您還需要聲明兩個構造函數:一個用於初始化沒有Component的外觀,另一個用於使用Component的數據初始化外觀。

+0

組件是外觀的一部分,我必須訪問此: terrorista 2014-10-19 11:06:21