忍受我。有3个班。Person 是具有姓名和年龄的基类。Child 是在学校有一个年级的派生类。Parent 是另一个可以有孩子的派生类(是或否)
在我们继续之前,有几件事我必须指出: 这是一个我想出来的练习,所以我可以练习一下继承。这个想法是最终得到一个向量,其中包含从基类到派生类对象的指针。
“程序”依赖于用户输入正确的值,没有错误检查等等,但这不是本练习的重点,所以这就是我没有做任何事情的原因。
非常感谢有关如何解决我遇到的问题的反馈。提前致谢。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person
{
private:
string m_name;
int m_age;
public:
Person(string name, int age)
{
m_name = name;
m_age = age;
}
string get_name()
{
return m_name;
}
virtual void info() =0;
};
class Child : public Person
{
private:
int m_grade;
public:
Child(string name, int age, int grade) : Person(name, age)
{
m_grade = grade;
}
void info()
{
cout <<"I am a child. I go to the " << m_grade << " grade."<<endl;
}
};
class Parent : public Person
{
private:
bool m_child;
public:
Parent(string name, int age, bool child) : Person(name, age)
{
m_child = child;
}
void info()
{
if(m_child == true)
{
cout << "I have a child." << endl;
}
else
{
cout << "I do not have a child" << endl;
}
}
};
vector create_list(const int& x)
{
vector <Person> a;
for(int a = 0; a < x; a++)
{
cout << "enter the name" << endl;
string o;
cin >> o;
cout << "enter the age" << endl;
int age;
cin >> age;
cout << "What would you like your person to be: a Child or a Parent?" << endl;
string choice;
cin >> choice;
if(choice == "Child")
{
cout << "enter it's grade" << endl;
int grade;
cin >> grade;
Child* c = new Child(o, age, grade);
a.push_back(c);
}
else
{
cout <<"enter if the parent has a child (yes/no)" << endl;
string wc;
cin >> wc;
if(wc == "yes")
{
Parent* p = new Parent(o, age, true);
a.push_back(p);
}
else
{
Parent* p = new Parent(o, age, false);
a.push_back(p);
}
}
}
return a;
}
int main()
{
cout << "How many people would you like to create?" << endl;
int x;
cin >> x;
vector<Person> a = create_list(x);
a[0]->getname();
return 0;
}