如何更改唯一指针向量的可见性
how to change the visibility of a vector of unique pointers
在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));
}
可以运行
相关文章:
- 如何更改唯一指针向量的可见性
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 限制静态库中符号的可见性 (MSVC/Visual C++)
- 班级成员可见性C++
- 内联模板函数的可见性
- Clang 是否可以在使用可见性属性时生成导入库(不带 __declspec(dllexport))?
- std::mutex 的发布-获取可见性保证是否仅适用于关键部分?
- 符号可见性和 gcc 警告
- C++/libscreen 无法更新可见性
- 在 C++11 线程中,std::mutex 对内存可见性有什么保证?
- C++继承构造函数的可见性
- CRTP - 嵌套叶类类型的可见性
- C++模板 - 实例之间的通用操作和成员可见性
- 放松的订单和线程间可见性
- GCC 6.x警告有关Lambda可见性
- C++ 中的Shared_ptr和内存可见性
- 静态库中的符号可见性和操作
- 未直接继承的基模板类成员的可见性
- 从shm_open() mmap()更改对共享内存的可见性
- 关于Lambdas,转换以功能指针以及私人数据成员的可见性