类型转换运算符:static_cast&dynamic_cast

1、static_cast:只有当类型转换有所定义,整个转换才会成功。

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;


void main()
{
	float x = 10.7f;
	cout << static_cast<int>(x) << endl;  //10:float转到int有所定义
	//cout << static_cast<string>(x) << endl;  //float不可以转到string,每天哟与定义
	string my = static_cast<string>("hello world");  //const char *可以转换位string
	copy(my.begin(), my.end(), ostream_iterator<char>(cout, ""));

	system("pause");
}  

2、dynamic_cast:

  • 将多态类型向下转型(downcast)为其实际类型
  • 运行期间进行检验

3、const_cast、reinterpret_cast

4、C语言中的转型()可以替换dynamic_cast之外的其他三种类型,也因此无法明确显示使用它的确切理由

5、新的转型操作符给了编译器更多信息,让编译器清楚知道它转型的理由

猜你喜欢

转载自blog.csdn.net/zhizhengguan/article/details/81366258