- C 标准库
- C 标准库
- C++ 标准库
- C++ 库 - 主页
- C++ 库 - <fstream>
- C++ 库 - <iomanip>
- C++ 库 - <ios>
- C++ 库 - <iosfwd>
- C++ 库 - <iostream>
- C++ 库 - <istream>
- C++ 库 - <ostream>
- C++ 库 - <sstream>
- C++ 库 - <streambuf>
- C++ 库 - <原子>
- C++ 库 - <复杂>
- C++ 库 - <异常>
- C++ 库 - <功能>
- C++ 库 - <限制>
- C++ 库 - <语言环境>
- C++ 库 - <内存>
- C++ 库 - <新>
- C++ 库 - <数字>
- C++ 库 - <正则表达式>
- C++ 库 - <stdexcept>
- C++ 库 - <字符串>
- C++ 库 - <线程>
- C++ 库 - <元组>
- C++ 库 - <类型信息>
- C++ 库 - <实用程序>
- C++ 库 - <valarray>
C++ 内存库 -dynamic_pointer_cast
描述
它返回正确类型的 sp 副本,其存储的指针从 U* 动态转换为 T*。
宣言
以下是 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;
参数
sp - 它是一个共享指针。
返回值
它返回正确类型的 sp 副本,其存储的指针从 U* 动态转换为 T*。
例外情况
noexcep - 它不会抛出任何异常。
例子
在下面的示例中解释了 std::dynamic_pointer_cast。
#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;
}
让我们编译并运行上面的程序,这将产生以下结果 -
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
内存.htm