【发布时间】:2020-07-05 09:07:35
【问题描述】:
在 ONG 类中,我创建了一个添加函数,将参与者(主管、管理员、员工)添加到参与者向量中。
std::vector<unique_ptr<Participant>> ls;
我试图将向量作为公共变量置于功能之外,但它不起作用
当我想在函数内部添加时,一切正常, 但是当我将列表置于功能之外时,它会给我一个错误
class ONG : public Participant {
private:
public:
std::vector<unique_ptr<Participant>> ls;
ONG() = default;
void add(unique_ptr<Participant> part) {
part->tipareste();
ls.emplace_back(std::move(part));
for (const auto& i : ls) {
i->tipareste();
}
}
};
这是完整的代码:
#include <iostream>
#include <assert.h>
#include <vector>
#include <memory>
#include <variant>
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>
using namespace std;
struct AtExit
{
~AtExit() { _CrtDumpMemoryLeaks(); }
} doAtExit;
class Participant {
public:
virtual void tipareste() = 0;
bool eVoluntar = true;
virtual ~Participant() = default;
};
class Personal : public Participant {
private:
string nume;
public:
Personal() = default;
Personal(string n) :nume{ n } {}
void tipareste() override {
cout << nume;
}
};
class Administrator : public Personal {
public:
std::unique_ptr<Personal> pers;
Administrator() = default;
Administrator(Personal* p) : pers{ p } {}
void tipareste() override {
cout << "administrator ";
pers->tipareste();
}
};
class Director : public Personal {
public:
std::unique_ptr<Personal> pers;
Director() = default;
Director(Personal* p) : pers{ p } {}
void tipareste() override {
cout << "director ";
pers->tipareste();
}
};
class Angajat :public Participant {
public:
std::unique_ptr<Participant> participant;
Angajat() = default;
Angajat(Participant* p) : participant{ p } { this->eVoluntar = false; /*p->eVoluntar = false;*/ }
void tipareste() override {
cout << "anjajat ";
participant->tipareste();
}
};
class ONG : public Participant {
private:
public:
ONG() = default;
std::vector<unique_ptr<Participant>> ls;
void add(unique_ptr<Participant> part) {
ls.emplace_back(std::move(part));
}
};
int main() {
ONG* ong{};
std::unique_ptr<Participant> aba = std::unique_ptr<Personal>(new Personal("Will"));
ong->add(std::move(aba));
}
【问题讨论】:
-
请比“它不起作用”和“它给我一个错误”更具体。
-
你得到的错误是什么?
-
一个问题是
main中的ong没有指向ONG实例。为什么ong是指针? -
另外一个问题是
ONG继承自Participant,但没有实现virtual void tipareste() = 0;。
标签: c++ vector polymorphism smart-pointers