基类指针的向量
Vector of pointers of the base class
听我说。有3个班。Person是带有姓名和年龄的基类。儿童是学校里有年级的派生类。Parent是另一个可以有子类的派生类(yes或no)
在我们继续之前,我必须指出几件事:这是我想到的一个练习,这样我就可以练习一下继承了。其思想是最终得到一个vector,其中包含从基类到派生类对象的指针。
"程序"依赖于用户输入正确的值,没有错误检查等等,但这不是本练习的重点,所以这就是为什么我没有对它做任何事情。
反馈如何解决我得到的问题是非常感谢。提前谢谢。
#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;
}
-
您在
for loop
中为vector<Person>
和int
使用相同的变量名称a
。因此,当您到达a.push_back(c);
行时,程序将认为a
是一个整数,而不是一个向量。让你的变量名唯一。
-
正如其他人所提到的,您的容器是
Person
类型的vector
,但是您实例化了Child *
和Parent *
类型的新派生类,因此您的vector
应该是Person*
类型。 同样的,函数的返回类型应该是 虽然在这种情况下没有必要,因为您的应用程序立即结束,但确保对
new
的每个调用对应于对delete
的调用是良好的实践。在这种情况下,您将编写一个free_list
方法,它遍历并删除列表中指向的每个Person对象。注意,vector本身不需要清理。
vector<Person*>
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 使用向量类的c++指针
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 如何更改唯一指针向量的可见性
- C++ 独特指针练习的向量
- C 中的向量指针的清晰图
- 当向量位于内部类中时,如何删除指向对象的向量指针
- std::向量指针
- 指向结构体的向量指针错误
- 删除指向指针的向量指针时出错
- 映射不同类型的向量指针
- 在c++中传递向量指针
- 虚拟类的向量:指针是干净的方法吗
- 如何从另一个向量/对象集构造新的向量/指针集
- 模型视图控制器- c++向量指针,太多的传递
- 为什么向量指针占用这么多内存?
- 删除条目向量指针的静态映射c++
- 复向量指针
- c++数组向量指针的初始化