简体   繁体   English

C ++:在父类中创建子类时出现问题

[英]C++: Problems creating a child class within a parent class

I'm working on a project that involves a class A that contains a few child classes (childB, childC, childD). 我正在一个项目中涉及一个包含几个子类(childB,childC,childD)的A类。 My overly simplified goal was to have something like this 我过度简化的目标是拥有这样的东西

#include <string>

class A{
public:
   childB cb;                       <<Error C4430: missing type specifier - int assumed
   childC cc;                       <<Error C4430:    "                            "
   childD cd;                       <<Error C4430:    "                            "

   A(){
      cc.setString("xyz");          <<Error C2039: 'cc' is not a member of A
   }
};

class childB : public A{
public:
   int value;
};

class childC : public A{
private:
   std::string str;
public:       
   void setString(std::string s){
      str = s;
   }
   std::string getString(std::string s){
      return str;
   }
};

class childD : public childB{
public:
   double value;
};

#include "classA.h"

int main (){
   A a;
   a.cc.getString();               <<Error C2228: left of '.getString()' must have class/struct/union
}

From this point I would have multiple things in main that would set the values of the different child classes, but when compiling I am getting numerous errors telling me that cb, cc, cd are not members of A. Additional errors are also listed. 从这一点出发,我将在main中有很多东西可以设置不同子类的值,但是在编译时,我收到许多错误,告诉我cb,cc,cd不是A的成员。还列出了其他错误。

Is there any reason why I wouldn't be able to add a child class to the parent class as shown? 有什么原因导致我无法如图所示将子类添加到父类吗?

I don't think it is possible for a parent class to have an instance of a child class. 我认为父类不可能有子类的实例。 You can use a child class pointers instead of child class objects for your purpose. 您可以使用子类指针代替子类对象。

Define child classes in separate header files. 在单独的头文件中定义子类。

Add forward declarations of child classes in parent class header file. 在父类头文件中添加子类的前向声明。

Use child class pointers instead of child class objects. 使用子类指针而不是子类对象。

Initialize child class pointer members of parent class with corresponding child class objects in a parent method such as init(). 在诸如init()之类的父方法中,使用相应的子类对象初始化父类的子类指针成员。 Do not initialize them in parent constructor since it will make an infinite recursion. 不要在父构造函数中初始化它们,因为它将进行无限递归。 You will have to move the init() method to a cpp file and include child class header files in that. 您将必须将init()方法移至cpp文件,并在其中包含子类头文件。

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

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