忍受我。有三类。人是具有名称和年龄的基类。孩子是在学校上课的派生班。家长是另一个派生类中谁能够有一个孩子(是或否)向量的基类指针
在我们继续之前有几件事我必须指出: 这是我想,这样我就可以练习继承有点锻炼。这个想法最终将包含一个向量,该向量包含从基类到派生类对象的指针。
该“程序”取决于用户输入正确的值,没有错误检查等,但这不是这个练习的重点,所以这就是为什么我没有做任何事情。
有关如何解决我遇到的问题的反馈非常感谢。提前致谢。
#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;
}
你忘了告诉我们你遇到了什么问题! –
'vector a;'应该是'vector a;'。但你不应该这样做。您应该使用* smart *指针的矢量或专门设计用于存放指针的集合,如'ptr_vector'。 –
你想要什么语义?例如,你是否打算让你的矢量拥有底层对象?如果向量被复制,那么这两个向量是否应该包含指向同一个基础对象的指针或者是否应该克隆该对象? –