【问题标题】:No matching conversion for functional-style cast from 'B *' to 'std::shared_ptr<A>'从 'B *' 到 'std::shared_ptr<A>' 的函数式转换没有匹配的转换
【发布时间】:2021-09-29 14:47:36
【问题描述】:

我有一个尝试初始化共享指针的简单应用程序。

#include <iostream>
#include <memory>
#include <algorithm>

class A {
public:
    A(){
        std::cout << "default ctor for A" << std::endl;
    }
    ~A(){
        std::cout << "default dtor for A" << std::endl;
    }
};

class B : A{
    B(){
        std::cout << "default ctor for B" << std::endl;
    }
    ~B(){
        std::cout << "default dtor for B" << std::endl;
    }
};



int main()
{

    auto ap = std::shared_ptr<A>(new B());
    
    return 0;
}

我收到了错误

No matching conversion for functional-style cast from 'B *' to 'std::shared_ptr<A>'

在这一行 自动 ap = std::shared_ptr(new B());

我在这里做错了什么?

【问题讨论】:

标签: class c++11 shared-ptr declaration access-control


【解决方案1】:

B 类应该声明为

class B : public A{
public:
    B(){
        std::cout << "default ctor for B" << std::endl;
    }
    ~B(){
        std::cout << "default dtor for B" << std::endl;
    }
};

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 2011-09-13
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 2019-08-06
    相关资源
    最近更新 更多