【问题标题】:Why am i getting this error? "Child undeclared?为什么我会收到此错误? “孩子未申报?
【发布时间】:2019-01-22 23:36:54
【问题描述】:

我正在编写一些代码来显示继承。 在这样做时,我想通过一个基类来说明它,该基类包含一个指针向量,该向量可以保存派生类的对象指针。

我在父类(基类)中的基函数“void addChild(string nm, string sm)”中收到“未声明子类”的错误。我确实理解它可能超出了基类的范围。 有人可以为我提供一个解决方案,我仍然可以从基类中实例化派生类的对象。 我想在基类中完成所有事情。 请澄清这是否可以并且是一个好习惯。如果没有,请提出一些想法。

这是我的代码:

#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;
    }
};

干杯!

【问题讨论】:

  • Child 类是否需要在使用它的Parent 类之前定义。
  • 是的。认识到。所以我只需要在基类主体中编写声明,并在基类之外和派生类下定义函数时使用基类名称和范围运算符。

标签: c++ inheritance vector base derived


【解决方案1】:

只需将函数的定义移出类的定义即可:

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 并返回一个指向它的指针,并添加如下内容:

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

【讨论】:

  • 哦,对了。我懂了。没想到。谢谢,兄弟!我试试看
  • 我还有一个问题。如果我想像这样向它添加另一个重载函数怎么办: void addChild(Child& c);这个现在给我一个错误
  • 我想我明白了。只需将其转换为基类指针
  • 所以它将是 addChild(Parent* p)。父指针持有派生对象的地址
猜你喜欢
  • 1970-01-01
  • 2018-06-22
  • 2016-01-01
  • 2015-08-02
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
相关资源
最近更新 更多