2012-12-22 132 views
0

忍受我。有三类。人是具有名称和年龄的基类。孩子是在学校上课的派生班。家长是另一个派生类中谁能够有一个孩子(是或否)向量的基类指针

在我们继续之前有几件事我必须指出: 这是我想,这样我就可以练习继承有点锻炼。这个想法最终将包含一个向量,该向量包含从基类到派生类对象的指针。

该“程序”取决于用户输入正确的值,没有错误检查等,但这不是这个练习的重点,所以这就是为什么我没有做任何事情。

有关如何解决我遇到的问题的反馈非常感谢。提前致谢。

#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; 
} 
+2

你忘了告诉我们你遇到了什么问题! –

+1

'vector a;'应该是'vector a;'。但你不应该这样做。您应该使用* smart *指针的矢量或专门设计用于存放指针的集合,如'ptr_vector'。 –

+0

你想要什么语义?例如,你是否打算让你的矢量拥有底层对象?如果向量被复制,那么这两个向量是否应该包含指向同一个基础对象的指针或者是否应该克隆该对象? –

回答

1
  1. 您正在使用相同的变量名a在您for loopvector<Person>int。所以,当你到达a.push_back(c);行时,程序会认为a是一个整数,而不是一个向量。

    使您的变量名称唯一。

  2. 正如其他人所说,你的容器是Person类型的vector,但您实例Child *类型和Parent *新的派生类,所以你vector应该是Person*类型。

  3. 在那同一个音符,你的函数的返回类型应为vector<Person*>

  4. 虽然因为你的应用程序立即结束,这是不是在这种情况下,必要的,这是很好的做法,以确保每次调用new对应致电delete。在这种情况下,您会编写一个free_list方法,它会通过并删除列表中指向的每个Person对象。请注意,矢量本身不需要清理。