简介
C++ 允许使用与函数调用语法类似的语法进行显式类型转换。
语法
simple-type-name ( expression-list )
备注
一个 简单类型的名称 ,后跟括在括号中的 表达式列表 使用指定的表达式构造指定类型的对象。 以下示例显示到类型 int 的显式类型转换:
int i = int( d );
下面的示例演示了一个 Point 类。
示例
// expre_Explicit_Type_Conversion_Operator.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class Point
{
public:
// Define default constructor.
Point() { _x = _y = 0; }
// Define another constructor.
Point( int X, int Y ) { _x = X; _y = Y; }
// Define "accessor" functions as
// reference types.
unsigned& x() { return _x; }
unsigned& y() { return _y; }
void Show() { cout << "x = " << _x << ", "
<< "y = " << _y << "\n"; }
private:
unsigned _x;
unsigned _y;
};
int main()
{
Point Point1, Point2;
// Assign Point1 the explicit conversion
// of ( 10, 10 ).
Point1 = Point( 10, 10 );
// Use x() as an l-value by assigning an explicit
// conversion of 20 to type unsigned.
Point1.x() = unsigned( 20 );
Point1.Show();
// Assign Point2 the default Point object.
Point2 = Point();
Point2.Show();
}
输出
Output
x = 20, y = 10
x = 0, y = 0
尽管前面的示例演示了使用常量的显式类型转换,但在对对象执行转换时,此方法也同样有效。 以下代码片段对此进行了演示:
int i = 7;
float d;
d = float( i );
还可以使用“cast”语法指定显式类型转换。 使用 cast 语法重写的上一个示例是:
d = (float)i;
当从单个值转换时,强制转换和函数样式转换都有相同的结果。 但是,在函数样式语法中,可以为转换指定多个自变量。 此差异对用户定义的类型非常重要。 请考虑 Point 类及其转换:
struct Point
{
Point( short x, short y ) { _x = x; _y = y; }
...
short _x, _y;
};
...
Point pt = Point( 3, 10 );
前面的示例使用函数样式转换,演示了如何将两个值 (一个值转换为 x ,一个用于 y) 转换为用户定义的类型 Point 。
注意
请谨慎使用显式类型转换,因其会重写 C++ 编译器的内置类型检查。
转换 表示法 必须用于转换为不具有 简单类型名称 (指针或引用类型的类型,例如) 。 若要转换为可使用 简单类型名称 表示的类型,可以使用任一形式编写。
在强制转换中的类型定义是非法的。
该博文为原创文章,未经博主同意不得转载,如同意转载请注明博文出处,本文章博客地址:https://blog.csdn.net/it_cplusplus/article/details/118501994