如何更改唯一指针向量的可见性

how to change the visibility of a vector of unique pointers

本文关键字:可见性 向量 指针 何更改 唯一      更新时间:2023-10-16

在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));


}

问题是类ONG是一个抽象类,因为它继承自具有纯虚函数的参与者。

如果定义

void tipareste() {
//Do stuff
}

ONG内部(或在ONG继承的类内部( 然后将ONG对象分配给ONG指针

int main() {
std::shared_ptr<ONG> ong = std::make_shared<ONG> ();
std::unique_ptr<Participant> aba = std::unique_ptr<Personal>(new Personal("Will"));
ong->add(std::move(aba));
}

可以运行