小白教程
所有教程
关于
Search
172.70.126.198
172.70.126.198
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Cpp casting operators”的源代码
本页内容
上一节:
Cpp_member_operators
下一节:
Cpp_pointer_operators
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:强制转换运算符}}[[Category:cpp operators|7]] = C++ 强制转换运算符 = [[cpp operators|C++ 运算符]] 强制转换运算符是一种特殊的运算符,它把一种数据类型转换为另一种数据类型。强制转换运算符是一元运算符,它的优先级与其他一元运算符相同。 大多数的 C++ 编译器都支持大部分通用的强制转换运算符: <pre> (type) expression </pre> 其中,type 是转换后的数据类型。下面列出了 C++ 支持的其他几种强制转换运算符: * '''const_cast<type> (expr):''' const_cast 运算符用于修改类型的 const / volatile 属性。除了 const 或 volatile 属性之外,目标类型必须与源类型相同。这种类型的转换主要是用来操作所传对象的 const 属性,可以加上 const 属性,也可以去掉 const 属性。 * '''dynamic_cast<type> (expr):''' dynamic_cast 在运行时执行转换,验证转换的有效性。如果转换未执行,则转换失败,表达式 expr 被判定为 null。dynamic_cast 执行动态转换时,type 必须是类的指针、类的引用或者 void*,如果 type 是类指针类型,那么 expr 也必须是一个指针,如果 type 是一个引用,那么 expr 也必须是一个引用。 * '''reinterpret_cast<type> (expr):''' reinterpret_cast 运算符把某种指针改为其他类型的指针。它可以把一个指针转换为一个整数,也可以把一个整数转换为一个指针。 * '''static_cast<type> (expr):''' static_cast 运算符执行非动态转换,没有运行时类检查来保证转换的安全性。例如,它可以用来把一个基类指针转换为派生类指针。 上述所有的强制转换运算符在使用类和对象时会用到。现在,请看下面的实例,理解 C++ 中如何使用一个简单的强制转换运算符。复制并黏贴下面的 C++ 程序到 test.cpp 文件中,编译并运行程序。 <pre> #include <iostream> using namespace std; int main() { double a = 21.09399; float b = 10.20; int c ; c = (int) a; cout << "Line 1 - Value of (int)a is :" << c << endl ; c = (int) b; cout << "Line 2 - Value of (int)b is :" << c << endl ; return 0; } </pre> 当上面的代码被编译和执行时,它会产生下列结果: <pre> Line 1 - Value of (int)a is :21 Line 2 - Value of (int)b is :10 </pre> [[cpp operators|C++ 运算符]]
返回至“
Cpp casting operators
”。
上一节:
Cpp_member_operators
下一节:
Cpp_pointer_operators