簡體   English   中英

基類的指針向量

[英]Vector of pointers of the base class

忍受我。 有3個班級。 人是具有名稱和年齡的基層。 兒童是派生類,在學校中有年級。 父母是另一個可以生孩子的派生階層(是或否)

在繼續之前,我必須指出兩點:這是我想過的一項練習,因此我可以稍微練習一下繼承。 這個想法的最終結果是一個向量,其中包含從基類到派生類對象的指針。

“程序”取決於用戶輸入正確的值,沒有錯誤檢查等,但這不是本練習的重點,因此這就是為什么我沒有做任何事情的原因。

非常感謝您提供有關如何解決我遇到的問題的反饋。 提前致謝。

#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 loopvector<Person>int使用相同的變量名a 因此,當您到達一行時a.push_back(c); 程序會認為a是整數,而不是向量。

    使變量名唯一。

  2. 就像其他人提到的那樣,您的容器是Person類型的vector ,但是您實例化了Child *Parent *類型的新派生類,因此您的vector應該是Person*類型。

  3. 同樣,函數的返回類型應為vector<Person*>

  4. 盡管在這種情況下沒有必要,因為您的應用程序會立即結束,但是最好確保對new每個調用都與delete的調用相對應。 在這種情況下,您將編寫一個free_list方法,該方法將遍歷並刪除列表中指向的每個Person對象。 請注意,向量本身不需要清理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM