【发布时间】: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