C风格的转换可以是固有的滥用,因为它会让你做的事情,可能没有意义,如去掉const或更改数据类型不改变基本的表示。C++引入了一个新的铸造的操作称为static_cast。静态浇铸的工作类似于C风格的演员,但它只会做标准类型转换,降低了疏忽的滥用潜力:
如上所述,编译器通常会抱怨当不安全的隐式强制执行。例如,考虑下面的程序:
铸造年int(4字节)到坦克(1字节)is potentially unsafe编译,and the will通常complain。in order to宣布to the编译你明确做某事你认识is potentially Unsafe(为了想做什,你应该使用静态)_演员:
1
2
3
int nValue1 = 10;
int nValue2 = 4;
float fValue = static_cast<float>(nValue1) / nValue2;
如上所述,编译器通常会抱怨当不安全的隐式强制执行。例如,考虑下面的程序:
1
2
int nValue = 48;
char ch = nValue; // implicit cast
铸造年int(4字节)到坦克(1字节)is potentially unsafe编译,and the will通常complain。in order to宣布to the编译你明确做某事你认识is potentially Unsafe(为了想做什,你应该使用静态)_演员:
1
2
int nValue = 48;
char ch = static_cast<char>(nValue);