我有两个A和B类,B继承自A。
如果我有一个shared_ptr<A>
对象,我知道它实际上是一个B子类型,我怎样才能执行动态转换来访问B的API(请记住我的对象是shared_ptr,而不仅仅是A?
答案 0 :(得分:35)
如果您只想从B
拨打电话,可以使用以下方法之一:
std::shared_ptr<A> ap = ...;
dynamic_cast<B&>(*ap).b_function();
if (B* bp = dynamic_cast<B*>(ap.get()) {
...
}
如果你真的想从std::shared_ptr<B>
获得std::shared_ptr<A>
,你可以使用
std::shared_ptr<B> bp = std::dynamic_pointer_cast<B>(ap);
答案 1 :(得分:6)
从上面链接复制的示例
// static_pointer_cast example
#include <iostream>
#include <memory>
struct A {
static const char* static_type;
const char* dynamic_type;
A() { dynamic_type = static_type; }
};
struct B: A {
static const char* static_type;
B() { dynamic_type = static_type; }
};
const char* A::static_type = "class A";
const char* B::static_type = "class B";
int main () {
std::shared_ptr<A> foo;
std::shared_ptr<B> bar;
bar = std::make_shared<B>();
foo = std::dynamic_pointer_cast<A>(bar);
std::cout << "foo's static type: " << foo->static_type << '\n';
std::cout << "foo's dynamic type: " << foo->dynamic_type << '\n';
std::cout << "bar's static type: " << bar->static_type << '\n';
std::cout << "bar's dynamic type: " << bar->dynamic_type << '\n';
return 0;
}
输出
foo's static type: class A
foo's dynamic type: class B
bar's static type: class B
bar's dynamic type: class B
答案 2 :(得分:1)
可能最好的方法是use the standard functions来投射shared_ptr