基类指针的向量

Vector of pointers of the base class

本文关键字:向量 指针 基类      更新时间:2023-10-16

听我说。有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;
}
  1. 您在for loop中为vector<Person>int使用相同的变量名称a。因此,当您到达 a.push_back(c);行时,程序将认为a是一个整数,而不是一个向量。

    让你的变量名唯一。

  2. 正如其他人所提到的,您的容器是Person类型的vector,但是您实例化了Child *Parent *类型的新派生类,因此您的vector应该是Person*类型。

  3. 同样的,函数的返回类型应该是vector<Person*>
  4. 虽然在这种情况下没有必要,因为您的应用程序立即结束,但确保对new的每个调用对应于对delete的调用是良好的实践。在这种情况下,您将编写一个free_list方法,它遍历并删除列表中指向的每个Person对象。注意,vector本身不需要清理。