将子类添加到基类向量

时间:2015-04-18 21:17:19

标签: c++ pointers vector

所以我拼命想弄清楚如何在C / C ++中将子类对象添加到基类向量中。我环顾四周,发现我需要使用指针和内存地址。除此之外,我还没有找到答案。

这个例子很简单。我有一本约会书,有一系列的每月,每日和一次性约会。这些需要存储在向量中。

另外,如果有人可以将我推荐给一个好的学习源指针 - 那将不胜感激。一般的好学习来源。我有一个教授,他班上70%的学生已经放弃了课程,我需要通过成绩。 T.T

#pragma once
#include "Appointment.h"
#include "Daily.h"
#include "Monthly.h"
#include "Onetime.h"

using namespace std; 

int main() {
    vector<Appointment *> appointmentBook;
    bool loop = true; 
    string input; 

    while (loop) {
        cout << "Enter the kind of appointment or q to quit: (d/m/o/q)" << endl; 
        cin >> input; 

        if (input == "d") {
            appointmentBook.push_back(Daily().read());
        } else if(input == "m") {

        }
        else if (input == "o") {

        }
        else {
            exit(0); 
        }
    }
    return 0; 
}

1 个答案:

答案 0 :(得分:0)

首先,以下可能工作:

vector<Appointment> apps;
AppointmentChild child;
apps.push_back(child);

但是在这里你可以在向量中复制你的对象,这很可能不是你想要的。另外,正如@TheUndeadFish在评论中提到的那样,这些副本也可能被切片,从而丢失了派生类中存储的数据,并可能还有其他一些麻烦。


现在指针是你可以使用的:

vector<Appointment*> apps;
auto child = new AppointmentChild;
apps.push_back(child);

delete child; // Don't forget to delete the object, when it is no more in use.

但更好的选择可能是shared_ptr

vector<shared_ptr<Appointment>> apps;
auto child = make_shared<AppointmentChild>();
apps.push_back(child);

此处您无需关心删除已分配的对象,shared_ptr会为您执行此操作。

相关问题