我的代码如下。我想将
std::shared_ptr<void>
转换为 std::shared_ptr<C>
,但没成功。
我收到以下错误:
main.cpp:74:63: error: no matching function for call to ‘std::shared_ptr<C>::shared_ptr(std::shared_ptr<void>&)’
std::shared_ptr<C> c = static_cast<std::shared_ptr<C>>(ptr);
我的代码:
class C
{
public:
C() {}
int val;
int set;
};
int main()
{
std::shared_ptr<C> cc = std::make_shared<C>();
cc->val = 1;
cc->set = 2;
std::shared_ptr<void> ptr = cc;
std::shared_ptr<C> c = static_cast<std::shared_ptr<C>>(ptr);
return 0;
}
为了将
shared_ptr<X>
转换为 shared_ptr<Y>
,您需要使用其中一种 特殊转换函数。
这些功能:
创建 std::shared_ptr 的新实例,其存储的指针为 使用强制转换表达式从 r 的存储指针获得。
对于静态转换,这将是
static_pointer_cast
:
std::shared_ptr<C> c = std::static_pointer_cast<C>(ptr);