C++基础——类型转换
c++类型转换函数
在C++中,进行类型转换的函数可以有很多种,以下是几种常见的类型转换方法:
使用C++的static_cast进行类型转换:
int i = 10;
double d = static_cast<double>(i);
使用C++的dynamic_cast进行类型转换,这主要用于类层次结构中的上下转换:
class Base { virtual void dummy() {} };
class Derived : public Base { /* ... */ };
Base* ptr = new Derived;
Derived* dptr = dynamic_cast<Derived*>(ptr);
使用C++的const_cast去除变量的const属性:
const int i = 10;
int* p = const_cast<int*>(&i);
使用C++的reinterpret_cast进行不安全的类型转换:
int* p = new int(65);
char* c = reinterpret_cast<char*>(p);
使用函数模板进行类型转换:
template <class T, class U>
T convert(U u) {
return static_cast<T>(u);
}
int i = convert<int>(3.14);
使用C++11标准中的std::function和std::bind进行类型转换:
#include <functional>
void print(int i) {
std::cout << i << std::endl;
}
std::function<void(int)> func = print;
func(5);