从“B *”到“std::shared_ptr<A>”的函数式转换没有匹配的转换

生活2hak

我有一个简单的应用程序,试图初始化一个共享的 ptr。

#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>'

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

我在这里做错了什么?

来自莫斯科的弗拉德

B类应该声明为

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

是否存在从std :: shared_ptr <T>到std :: shared_ptr <const T>的隐式转换?

我可以定义从std :: function到std :: shared_ptr <MyClass>的隐式转换吗?

移动 std::shared_ptr 的函数声明

将std :: shared_ptr <char>转换为std :: shared_ptr <unsigned char>

为什么不将shared_ptr派生到隐式转换为shared_ptr到Base

将std :: shared_ptr <T>传递给采用std :: shared_ptr <const T>的函数?

将'this'强制转换为std :: shared_ptr

将std :: shared_ptr <T>转换为void *

将std :: shared_ptr传递给函数对象到std :: thread

std::shared_ptr<Derived> 如何在没有编译器错误的情况下转换为 std::shared_ptr<Base> ?

无法将参数1从'std :: shared_ptr <ChaseState>转换为'std :: shared_ptr <State <Cow >>

使用相同的函数但具有不同的重载来转换std :: tr1 :: shared_ptr <T>和std :: shared_ptr <T>

将shared_ptr传递给std :: function(成员函数)

使用工厂函数创建std :: shared_ptr

std :: shared_ptr`的副本构造函数是原子还是`reset()`?

std :: shared_ptr的控制块中的虚函数

std :: shared_ptr复制构造函数线程安全

std :: shared_ptr和std :: experimental :: atomic_shared_ptr有什么区别?

我对std :: vector <shared_ptr>有疑问

如何从std :: shared_ptr转换为std :: unique_ptr?

在C ++中,空std :: shared_ptr和空std :: shared_ptr有什么区别?

将std :: map <int,std :: shared_ptr <Base >>转换为std :: map <int,std :: shared_ptr <Derived >>的最有效的安全方法

将std :: shared_ptr隐式转换为指针类型

具有可变构造函数的类模板;将参数存储到std :: vector <std :: shared_ptr <>

与std :: shared_ptr和std :: unique_ptr相比,std :: optional`有什么优势?

从“int”到“ItemType”的函数式转换没有匹配的转换

错误:没有用于初始化“std::shared_ptr<uint8_t []>”的匹配构造函数

将对具有 shared_ptr 作为值的映射的引用转换为对具有 shared_ptr 到 const 作为值的映射的引用

std :: unique_ptr和std :: shared_ptr作为虚拟函数的参数