我可以在另一个类中创建一个类吗?并且一起打电话

时间:2014-10-19 02:25:56

标签: c++ class

我是c ++的新手,所以我希望你可以帮助我。

我有这个类外观,我展示了一些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);

我试图在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>  

我不知道我是否解释了我想要的东西,但有人可以帮助我吗? :)

2 个答案:

答案 0 :(得分:0)

为此,您需要更改构造函数以包含组件类的数据。

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

然后在构造函数中调用Component的构造函数。

但这引起了设计问题。如果你可以初始化你的组件,这意味着它只是你想要做的逻辑组,我建议使用命名法来代替comp_Ambient。

如果您希望班级中有多个组件,那么您不想在构造函数中初始化它。

我看到使用这种设计的另一个原因是能够在其他对象上使用组件,然后,不要把它放在课堂上。

答案 1 :(得分:0)

您是否需要完全访问组件成员和功能?如果是这样,我会看到两个可能的问题答案。最简单的方法是创建一个继承自Appearances和Component的派生类。例如,您可以声明class Design: public Appearances, public Component。虽然多重继承有时会使设计复杂化,但它似乎是最直接的选择。查看更多here

如果您想将功能添加到现有的Appearances类中,可以通过将Component设置为Appearances的朋友类来完成。这是通过将行friend class Appearances;添加到Component类来完成的,它允许Appearances访问Component的所有成员。在这种情况下,您还需要声明两个构造函数:一个用于初始化不带Component的Appearances,另一个用于使用Component的数据初始化Appearances。