为什么我会收到此错误? “Child 未申报?

Why am i getting this error? "Child undeclared?

我正在编写一些代码来显示继承。 在这样做时,我想通过一个基 class 来说明它,该基 class 包含一个指针向量,可以容纳 object 个派生 class.

的指针

我收到此错误,基本函数 "void addChild(string nm, string sm)" 中的 "Child class is undeclared" 在 Parents class(基本 class)中。我确实知道它可能超出了基础 class 的范围。 有人可以为我提供一个解决方案,我仍然可以从基础 class 中实例化派生 class 的 object。 我想在基地 class 内完成所有事情。 请澄清这是否可以,是否是一个好习惯。如果没有,请提出一些想法。

这是我的代码:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Parents // base class
{
    vector <Parents*> fam;

protected:
    string firstName;
    string lastName;
public:
    Parents()
    {
        //default constructor              
    }
    Parents(string fn, string ln)
    {
        firstName = fn;
        lastName = ln;
    }
    void displayChildren()
    {
        if (fam.empty())
        {
            cout << "Vector is empty" << endl;
        }
        else
        {
            for (unsigned int i = 0; i < fam.size(); i++)
            {
                std::cout, fam.at(i);
            }
        }
    }
    void displayParentsInfo(Parents& const par)
    {
        cout << "First name : " << par.firstName << endl;
        cout << "Last name  : " << par.lastName << endl;
    }
    void addChild(string nm, string sm)
    {
        Child* c1 = new Child(nm, sm);      
        fam.push_back(c1);
    }
};

class Child : public Parents //derived class
{
    string firstname;
    string surname;

public:
    Child()
    {
        //default constructor
    }
    Child(string a, string b)
    {
        firstname = a;
        surname = b;
    }
    //~Child()
    //{
        //destructor called
    //}
    void displayChildInfo(Child & const c)
    {
        cout << "Child's firstname : " << c.firstname;
        cout << "Child's surname   : " << c.surname;
    }
};

干杯!

只需将函数的定义移出 class:

的定义
class Parents // base class
{
  ...
  void addChild(string nm, string sm);
};

class Child : public Parents //derived class
{
  ...
};

void Parents::addChild(string nm, string sm)
{
    Parents* c1 = new Child(nm, sm);      
    fam.push_back(c1);
}

至于好的做法,最好有一个非成员函数来准备 Child 和 returns 指向它的指针,并添加如下内容:

void Parents::addToFam(Parents* c1)
{
    fam.push_back(c1);
}