基类包含派生类的实例

基类包含派生类的实例

本文介绍了c ++基类包含派生类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以向我解释如何实现类似这样的东西:

I was wondering if someone could explain to me how I might be able to implement something similar to this:

namespace advanced_cpp_oop
{
  class A
  {
    B b;
  };

  class B : public A
  {
  };
}

int main()
{
}

基类的实例可以包含派生类的实例?当上面的代码编译时会产生以下错误:

Where an instance of a base class can contain an instance of a derived class? When the above code is compiled the following error is generated:

g++ advanced_cpp_oop.cpp
advanced_cpp_oop.cpp:8:5: error: ‘B’ does not name a type

编译是:

public class AdvancedCppOop
{
  public static void main(String[] args)
  {
    A a;
  }
}

class A
{
  B b;
}

class B extends A
{
}


b $ b

感谢

Thanks

推荐答案

您需要一个指针和一个转发声明:

You need to a pointer and a forward declaration:

namespace advanced_cpp_oop
{
  class B;

  class A
  {
    B* b;
  };

  class B : public A
  {
  };
}



在您的C ++代码中,您将创建一个 class B 在里面A类,这是不可能的,因为编译器还不知道任何东西(特别是大小) class B 。

In your C++ code, you are creating an instance of your class B inside class A, which is not possible since the compiler does not yet know anything (especially not the size) of class B.

使用我的答案中的代码,您需要动态分配 B 并将其分配给代码中其他位置的 b 指针。

With the code from my answer, you need to dynamically allocate an instance of class B and assign it to the b pointer somewhere else in your code.

从设计角度来看,这不是真的有意义,因为父类不应该依赖于子类。

On a side note, from design perspective, this does not really make sense since a parent class should not depend on a sub class.

这篇关于c ++基类包含派生类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:37