/*
* dynamic_pointer_cast
*/
描述 (Description)
它返回一个正确类型的sp副本,其存储的指针从U *动态地转换为T *。
声明 (Declaration)
以下是std :: dynamic_pointer_cast的声明。
template <class T, class U>
shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;
C++11
template <class T, class U>
shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;
参数 (Parameters)
sp - 它是一个共享指针。
返回值 (Return Value)
它返回一个正确类型的sp副本,其存储的指针从U *动态地转换为T *。
异常 (Exceptions)
noexcep - 它不会抛出任何异常。
/*
* 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 = "sample text A";
const char* B::static_type = "sample text 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;
}文章来源:https://www.toymoban.com/news/detail-605707.html
/*
foo's static type: sample text A
foo's dynamic type: sample text B
bar's static type: sample text B
bar's dynamic type: sample text B
*/文章来源地址https://www.toymoban.com/news/detail-605707.html
到了这里,关于c++ 之 dynamic_pointer_cast的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!