C++附带了四个内置的强制转换.
static_castdynamic_castconst_castreinterpret_cast不要说皱眉头C (style*)cast.
另外,boost提供了一个lexical_cast,你还有其他有用的演员阵容吗?
Joh*_*itb 10
我最喜欢和最喜爱的演员是implicit_cast.只有在可以隐式转换类型时才会成功.
用于从某些类型转换void*为某个派生类或从某个派生类转换为基类(如果要选择重载函数或构造函数的特定实例)或安全地添加常量资格以及您真正需要隐式转换的任何其他场景发生,甚至static_cast太强大了.
另请阅读C++如何选择要调用的重载.
boost/implicit_cast.hpp.如果需要,您也可以将其添加到代码集合中
template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }
Run Code Online (Sandbox Code Playgroud)
还有函数样式转换,看起来像函数或构造函数调用.这解析为类的构造函数调用,并且(更一般地)解析为所有其他类型的C样式转换.
例子:
int x = int(1.0); // equals `(int)1.0`
string s = string("x"); // equals call to constructor
Run Code Online (Sandbox Code Playgroud)
对构造函数的调用也可以使用显式强制转换(除了C样式的强制转换也可以使用):
string s = static_cast<string>("x"); // is the same as above!
Run Code Online (Sandbox Code Playgroud)
小智 8
值得记住的是,构造函数也可以被视为强制转换,编译器将使用它来执行类似转换的转换.例如:
class Person {
public:
Person( const std::string & name );
...
};
Run Code Online (Sandbox Code Playgroud)
Person构造函数从字符串 - > Person执行转换:
Person p = Person( "fred" );
Run Code Online (Sandbox Code Playgroud)
当字符串需要与某个人交谈时,编译器将使用它:
void PrintPerson( const Person & p ) {
...
}
Run Code Online (Sandbox Code Playgroud)
编译器现在可以将字符串转换为Person:
string name = "fred";
PrintPerson( name );
Run Code Online (Sandbox Code Playgroud)
但请注意,它不能这样做:
PrintPerson( "fred" );
Run Code Online (Sandbox Code Playgroud)
因为这需要编译器构建一系列转换.
编辑:我发布了有关转换主题的后续问题 - 请参阅C++隐式转换.