c++ - 智能指针 : cast between base and derived classes

标签 c++ inheritance casting smart-pointers

假设你有这样一个函数:

SmartPtr<A> doSomething(SmartPtr<A> a);

像这样的类:

class A { }
class B : public A { }

现在我这样做:

SmartPtr<A> foo = new B();
doSomething(foo);

现在,我想取回一个 SmartPtr<B>来自 doSomething 的对象.

SmartPtr<B> b = doSomething(foo); 

这可能吗?我需要做什么样的选角?
现在,我刚发现一些我认为丑陋的东西:

B* b = (B*)doSomething().get()

重要说明:我无权访问 SmartPtrdoSomething()代码。

最佳答案

除了这样做,你还可以这样做:

B *b = dynamic_cast< B* >( doSomething.get() );

但是你必须检查 b 是否为 NULL。

关于c++ - 智能指针 : cast between base and derived classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5633695/

相关文章:

c - 错误: incompatible types when initializing type

C++ 捕获 fork 子 cout

c# - 接口(interface)继承接口(interface)

python - 在Python中扩展现有的类实例

class - 在 Swift 中,如何遍历对象的类继承?

postgresql - 我无法修复这个看似简单的与转换相关的 postgresql 错误

c++ - 如何比较类中的 bool 值?

C++ Biginteger,这是什么意思?

c++ - boost线程notify_all()和sleep()

java - Java 将 int 转换为 double