简体   繁体   English

C ++的组成和初始化

[英]c++ composition and initialization

I have the following (examplery) classes 我有以下(示例)类

class ComponentA : public ComponentBase {
  Renderer renderer;
}

class Renderer {
  Renderer(std::vector<float> verts) : vertices(verts){};
  std::vector<float> vertices;
}

I'd like to keep my derived component classes flexible, so there could be many different renderers and of course other objects that are part of the component. 我想使派生的组件类保持灵活,因此可以有很多不同的渲染器,当然还有其他对象也属于该组件。

The renderer class does not have a default constructor, so I'd have to initialise it in the component's initialiser list or directly in the component's header file. renderer类没有默认的构造函数,因此我必须在组件的初始化程序列表中或直接在组件的头文件中对其进行初始化。 Alternatively I could add a default constructor to renderer, but what if I have a class where a default constructor doesn't make sense or I don't want to implement one since it would require extra handling (ie setting a flag that the object isn't properly initialised)? 另外,我可以在渲染器中添加默认构造函数,但是如果我有一个类,其中的默认构造函数没有意义或者我不想实现一个默认构造函数,那将需要额外的处理(即,设置对象为没有正确初始化)?

Additionally, the renderer could potentially not be necessary for the whole lifetime of the component, which would again require renderer to have some sort of "off" switch. 另外,在组件的整个生命周期中,渲染器可能不是必需的,这将再次要求渲染器具有某种“关闭”开关。

Now of course a (unique) pointer would solve the problem, but I'd like to avoid that if not necessary. 现在,当然可以使用一个(唯一的)指针来解决该问题,但是如果没有必要,我想避免这种情况。

Are there any idioms/solutions to this problem I could use to handle these cases? 我可以使用任何惯用语/解决方案来解决这些问题吗?

Is what you are looking for not just classical inherritance? 您在寻找的不仅仅是古典继承吗? Ie something Like 即像

class ComponentA : public ComponentBase {
  RendererBase& renderer;
  ComponentA(RederBase& r):renderer(r) {} 
}

class RenderBase {
  // Maybe some mandetory virtual functions in here
};

class RendererTypeFloat : public RenderBase {
  RendererTypeFloat(std::vector<float> verts) : vertices(verts){};
  std::vector<float> vertices;
}

class RendererTypeInt : public RenderBase {
  RendererTypeInt(std::vector<int> verts) : vertices(verts){};
  std::vector<int> vertices;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM