Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将抽象类作为函数参数传递,然后在原始类超出范围后使用?_C++_Reference_Abstract Class - Fatal编程技术网

C++ 如何将抽象类作为函数参数传递,然后在原始类超出范围后使用?

C++ 如何将抽象类作为函数参数传递,然后在原始类超出范围后使用?,c++,reference,abstract-class,C++,Reference,Abstract Class,我有以下抽象类 struct Interface { virtual ~Interface() = default; virtual void Do() = 0; }; 我有一个或多个实现接口的具体类 struct ImplA final: Interface{ virtual void Do() override {printf("DO IN ImplA\n");} }; struct ImplB final: Interface{ vi

我有以下抽象类

struct Interface {
    virtual ~Interface() = default;
    virtual void Do() = 0;
};
我有一个或多个实现
接口的具体类

struct ImplA final: Interface{
    virtual void Do() override {printf("DO IN ImplA\n");}
};

struct ImplB final: Interface{
    virtual void Do() override {printf("DO IN ImplB\n");}
};
这是我的主要代码(它只是抽象出来的)

下面是该方法的外观 我使用了一个全局容器来表示它也在方法的范围之外。它们将在以后使用

std::vector<std::unique_ptr<Container>> containers;
void Method(Interface& myInterfaceReference) {
    // to show that it lives out of scope of this method
    // how should the reference be passed to Container class
    // such that it can be used even after original instances are out of scope
    containers.emplace_back(new Container());
}

将智能指针存储在
容器中
,以便它控制引用对象的生存期:

struct Container {
    std::unique_ptr<Interface> pointerToInterface;
传递智能指针:

Container(std::unique_ptr<Interface> i)
    : pointerToInterface(std::move(i)) {}
std::vector<Container> containers;
void Method(std::unique_ptr<Interface> i) {
    containers.emplace_back(std::move(i));


Method(std::make_unique<ImplA>());
Method(std::make_unique<ImplB>());
容器(std::unique\u ptr i)
:pointerPointerface(std::move(i)){}
如何将抽象类作为函数参数传递,然后在原始类超出范围后使用

传递智能指针:

Container(std::unique_ptr<Interface> i)
    : pointerToInterface(std::move(i)) {}
std::vector<Container> containers;
void Method(std::unique_ptr<Interface> i) {
    containers.emplace_back(std::move(i));


Method(std::make_unique<ImplA>());
Method(std::make_unique<ImplB>());
std::向量容器;
无效方法(标准::唯一\u ptr i){
集装箱。安置(标准::移动(i));
方法(std::make_unique());
方法(std::make_unique());

你可能需要一个
克隆
虚拟函数。@Jarod42,非常感谢你的回答。你能给我举个例子吗?如果我理解正确,在这种情况下,我应该
新建
ImplA和ImplB,而不是在堆栈上自动创建它们?@HasanEmrahSüngüI添加了一个例子。非常感谢。我我刚刚看到了您发布的示例。因此,无论是哪种情况,我都应该在堆上进行分配understand@HasanEmrahSüngü是的。存储多态对象通常需要动态存储。再次感谢您的详细解释。我也有一个非常类似的使用智能指针的方法,但我不想在he上分配ap(因为容器类已经在堆上分配了,并且希望借助它)。
std::vector<Container> containers;
void Method(std::unique_ptr<Interface> i) {
    containers.emplace_back(std::move(i));


Method(std::make_unique<ImplA>());
Method(std::make_unique<ImplB>());