Ell*_*Ell 12 c++ casting type-conversion conversion-operator
什么是类型转换?什么是类型转换?
我什么时候应该使用它们?
细节:对不起,如果这是一个明显的问题; 我是C++的新手,来自红宝石背景,习惯于to_s等等to_i.
Ste*_*sop 16
转换是指将值转换为其他类型的转换.结果是目标类型的值,并且有什么输出值由(源类型的)输入产生的规则.
例如:
int i = 3;
unsigned int j;
j = i; // the value of "i" is converted to "unsigned int".
Run Code Online (Sandbox Code Playgroud)
结果是unsigned int等于imodulo 的值,UINT_MAX+1此规则是语言的一部分.因此,在这种情况下,值(英文)仍然是"3",但它是无符号的int值3,这与有符号的int值3略有不同.
请注意,转换是自动发生的,我们只是在需要unsigned int值的位置使用了signed int值,而语言定义了这意味着什么,而没有我们实际上说我们正在转换.这被称为"隐式转换".
" Casting "是一种明确的转换.
例如:
unsigned int k = (unsigned int)i;
long l = long(i);
unsigned int m = static_cast<unsigned int>(i);
Run Code Online (Sandbox Code Playgroud)
都是演员.具体来说,根据标准的5.4/2,k使用cast-expression,根据5.2.3/1,l使用相同的东西(除了我使用了不同的类型).m使用"类型转换运算符"(static_cast),但标准的其他部分也称为"强制转换".
用户定义的类型可以定义"转换函数",它提供将类型转换为另一种类型的特定规则,单引号构造函数也用于转换:
struct Foo {
int a;
Foo(int b) : a(b) {} // single-arg constructor
Foo(int b, int c) : a(b+c) {} // two-arg constructor
operator float () { return float(a); } // conversion function
};
Foo f(3,4); // two-arg constructor
f = static_cast<Foo>(4); // conversion: single-arg constructor is called
float g = f; // conversion: conversion function is called
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6320 次 |
| 最近记录: |