首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >std::unique_ptr中的抽象类作为函数不工作的返回

std::unique_ptr中的抽象类作为函数不工作的返回
EN

Stack Overflow用户
提问于 2020-08-28 02:43:00
回答 2查看 600关注 0票数 1
代码语言:javascript
运行
复制
class Base{
public:
    virtual std::string typeName() = 0;
    virtual ~Base() = 0;
};
Base::~Base(){}

class D1 : public Base{
public:
    std::string typeName();
    std::vector<std::unique_ptr<Base>> children;
    ~D1(){};
};
class D2 : public Base{
public:
    std::string typeName();
    std::unique_ptr<Base> child;
    ~D2(){};
};
std::string D1::typeName(){
    return "class D1";
}
std::string D2::typeName(){
    return "class D2";   
}

class Program{
public:
   std::unique_ptr<Base> D1Generic();
   std::unique_ptr<Base> D2Generic();
};
std::unique_ptr<Base> Program::D1Generic(){
    return std::make_unique<Base>(D1{});
}
std::unique_ptr<Base> Program::D2Generic(){
    return std::make_unique<Base>(D2{});
}

这段代码只是一个简单的版本,它复制了我所面临的问题。我的设计意图是在一棵树上创建一个访问者模式,并将其转化为另一棵树。

我已经将眼前的问题缩小到了D1GenericD2Generic函数。我在这里的目的是创建一个可扩展的接口,允许Base的多个子类在多态上作为唯一的指针变量进行匹配。

我发现了这些错误:

代码语言:javascript
运行
复制
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0/../../../../include/c++/7.5.0/bits/unique_ptr.h:821:34: error: 
      allocating an object of abstract class type 'Base'
    { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
                                 ^
main.cpp:38:17: note: in instantiation of function template specialization
      'std::make_unique<Base, D1>' requested here
    return std::make_unique<Base>(D1{});
                ^
main.cpp:8:25: note: unimplemented pure virtual method 'typeName' in 'Base'
    virtual std::string typeName() = 0;
                        ^
main.cpp:9:13: note: unimplemented pure virtual method '~Base' in 'Base'
    virtual ~Base() = 0;
            ^
In file included from main.cpp:4:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0/../../../../include/c++/7.5.0/memory:80:
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0/../../../../include/c++/7.5.0/bits/unique_ptr.h:821:34: error: 
      allocating an object of abstract class type 'Base'
    { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
                                 ^
main.cpp:41:17: note: in instantiation of function template specialization
      'std::make_unique<Base, D2>' requested here
    return std::make_unique<Base>(D2{});
                ^
2 errors generated.
EN

Stack Overflow用户

发布于 2020-08-28 02:47:12

试试这个:

代码语言:javascript
运行
复制
std::unique_ptr<Base> Program::D1Generic() {
    return (std::unique_ptr<Base>)new D1();
}
std::unique_ptr<Base> Program::D2Generic() {
    return (std::unique_ptr<Base>)new D2();
}
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63626718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档