简体   繁体   English

继承类的组成

[英]composition of Inherited classes

There is probably already a question about this but I couldn't find it. 可能已经有一个问题了,但我找不到。

I'm sure there is a simple solution but I can't see it. 我敢肯定有一个简单的解决方案,但我看不到。

Let's say you have the following: 假设您具有以下条件:

class FooBase
{
protected:
    BarBase myInstance;
}

class FooChild : public FooBase
{
protected:
    BarChild myInstance;
}

class BarChild : public BarBase
{
}

So basically, you want to use the derived version of BarBase in the FooChild class. 因此,基本上,您想在FooChild类中使用BarBase的派生版本。

I think that in the above code, there will be 2 different instances of myInstance (one BarBase and one BarChild). 我认为在上面的代码中,将有2个不同的myInstance实例(一个BarBase和一个BarChild)。

I would like to have only one instance so that I can use BarBase in FooBase and I can use BarChild in FooChild. 我只想拥有一个实例,这样我就可以在FooBase中使用BarBase,而在FooChild中使用BarChild。

Is there an elegant solution? 有一个优雅的解决方案吗?

Can you try something like this so that only one instance is created. 您是否可以尝试这样的操作,以便仅创建一个实例。

#include <iostream>

class BarBase
{
}
;
class BarChild : public BarBase
{
}
;

class FooBase
{
public:
  FooBase(BarBase* baseBar);
protected:
  BarBase* myInstance;
}
;


class FooChild : public FooBase
{
public:
  FooChild(BarBase* base)
;
}
;


FooBase::FooBase(BarBase* baseBar)
{
  myInstance = baseBar;
}

FooChild::FooChild(BarBase* childBar) : FooBase(childBar)
{

}

int main()
{
  BarChild *bc = new BarChild();
  FooChild fc(bc);
}

I don't know either this is the right solution or it's elegant one ;) 我不知道这是正确的解决方案还是优雅的解决方案;)

Are templates an option? 可以选择模板吗?

tempalate <typename T = BarBase>
class FooBase{
protected:
    T myInstance;
};

class FooChild : public FooBase<BarChild> {};

If I use int and double to test this works as desired using only one member variable: http://ideone.com/nOfR5x 如果我使用intdouble进行测试,则仅使用一个成员变量即可按需工作http : //ideone.com/nOfR5x

It does however require declarations of FooBase to be followed by angle brackets. 但是,它确实需要在FooBase声明后FooBase尖括号。

Virtualization is what you're looking for i believe. 我相信,虚拟化是您正在寻找的东西。 Give it a look. 看看吧。 You can simply use a Constructor Method which creates those variables. 您可以简单地使用构造器方法来创建这些变量。 If you create a derived class, then it calls that class's constructor, which creates that variable. 如果创建派生类,则它将调用该类的构造函数,该构造函数将创建该变量。

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

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