我如何使用std :: shared

编程入门 行业动态 更新时间:2024-10-23 19:28:09
本文介绍了我如何使用std :: shared_ptr实现多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经看到关于此主题的其他一些问题,但仍未找到答案 - 我想我错过了一些东西:

我定义了两个简单的测试类:

I defined two simple test classes:

class TestBase { public: TestBase ( ) { }; ~ TestBase ( ) { }; protected: inline virtual int getInt ( ) { return 0; } }; class TestDerived : public TestBase { protected: inline int getInt ( ) override { return 1; } };

我使用 std :: shared_ptr声明typedefs以简化它们的使用:

typedef std::shared_ptr<TestBase> spBase; typedef std::shared_ptr<TestDerived> spDerived;

问题:我无法编译代码来使用这些 shared_ptr

Problem: I cannot compile code to use these shared_ptr declarations polymorphically, even though base in all these cases is actually an instance of spDerived:

spBase base; spDerived derived = static_cast < spDerived > ( base );

错误:没有匹配函数调用'std :: shared_ptr :: shared_ptr(spBase&)

error: no matching function for call to ‘std::shared_ptr::shared_ptr(spBase&)

spDerived derived = dynamic_cast < spDerived > ( base );

error:can not dynamic_cast'base'(type'spBase {aka class std :: shared_ptr}'(target不是指针或引用)

error: cannot dynamic_cast ‘base’ (of type ‘spBase {aka class std::shared_ptr}’) to type ‘spDerived {aka class std::shared_ptr}’ (target is not pointer or reference)

spDerived derived = static_pointer_cast < spDerived > ( base );

错误:从'std :: shared_ptr'转换为非标量键入'spDerived {aka std :: shared_ptr}'请求 $ b

error: conversion from ‘std::shared_ptr >’ to non-scalar type ‘spDerived {aka std::shared_ptr}’ requested

spDerived derived = dynamic_pointer_cast < spDerived > ( base );

错误:从'std :: shared_ptr'转换为非标量键入'spDerived {aka std :: shared_ptr}'请求

error: conversion from ‘std::shared_ptr >’ to non-scalar type ‘spDerived {aka std::shared_ptr}’ requested

在默认的GCC工具链的Ubuntu 14.04盒子上使用C ++ 11。编译器是gcc-4.9。 我做错了什么?不能使用多态的shared_pointer?

I'm using C++11 on an Ubuntu 14.04 box with the default GCC tool chain. Compiler is gcc-4.9. What am I doing wrong? Can't a shared_pointer be used polymorphically?

推荐答案

传入 std :: static_pointer_cast 和 std :: dynamic_pointer_cast 作为第一个类型模板参数是转换的指针类型本身的类型,而不是 smart 指针类型:

static_pointer_cast<T>(arg); .~~~^ v template <class T, class U> .~~~~^ v shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r); dynamic_pointer_cast<T>(arg); .~~~~^ v template <class T, class U> .~~~~^ v shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& r);

有了这个说法,你可以这样称呼它:

With that said, you could call it like below:

spBase base = std::make_shared<TestDerived>(); spDerived derived = std::dynamic_pointer_cast<spDerived::element_type>(base); // or: spDerived derived2 = std::dynamic_pointer_cast<TestDerived>(base);

更多推荐

我如何使用std :: shared

本文发布于:2023-07-30 00:28:24,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   std   shared

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!