C ++中的类型转换/铸造混淆 [英] Type Conversion/Casting Confusion in C++

查看:184
本文介绍了C ++中的类型转换/铸造混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释什么是类型转换 ?我应该在什么时候使用它们?对不起,如果这是一个明显的问题,但我是新的,来自一个红宝石背景,我习惯了to_s和to_i等!提前感谢,

Can somebody explain to me, what is Type Conversion and what is Type Casting? When should I use each of them? I'm sorry if this is an obvious question, but I'm new and come from a ruby background and I'm used to "to_s" and "to_i" and the like! Thanks in advance, ell

推荐答案

转换是指某个值转换为不同类型。结果是目标类型的值,并且有什么输出值来自什么输入(源类型)的规则。

Conversion is when a value is, um, converted to a different type. The result is a value of the target type, and there are rules for what output value results from what input (of the source type).

例如:

int i = 3;
unsigned int j;
j = i; // the value of "i" is converted to "unsigned int".

结果是 unsigned int 等于 i modulo UINT_MAX + 1 ,并且此规则是语言的一部分。所以,在这种情况下,值(英语)仍然是3,但它是一个无符号整数值3,这是一个微妙的不同于一个有符号的整数值3。

The result is the unsigned int value that is equal to i modulo UINT_MAX+1, and this rule is part of the language. So, in this case the value (in English) is still "3", but it's an unsigned int value of 3, which is subtly different from a signed int value of 3.

请注意,转换是自动进行的,我们只是在需要unsigned int值的位置使用了一个signed int值,语言定义了没有我们真正说我们正在转换的意思。这称为隐式转换。

Note that conversion happened automatically, we just used a signed int value in a position where an unsigned int value is required, and the language defines what that means without us actually saying that we're converting. That's called an "implicit conversion".

铸造是一个显式转换。

例如:

unsigned int k = (unsigned int)i;
long l = long(i);
unsigned int m = static_cast<unsigned int>(i);

都是强制转换。具体来说,根据标准的5.4 / 2, k 使用一个 cast-expression ,根据5.2.3 / 1, l 使用等效的东西(除了我使用了不同的类型)。 m 使用类型转换运算符( static_cast ),但标准的其他部分称为 。

are all casts. Specifically, according to 5.4/2 of the standard, k uses a cast-expression, and according to 5.2.3/1, l uses an equivalent thing (except that I've used a different type). m uses a "type conversion operator" (static_cast), but other parts of the standard refer to those as "casts" too.

用户定义的类型可以定义转换函数,这些函数提供了将类型转换为另一种类型的特定规则,并且转换中也使用单一参数构造函数:

User-defined types can define "conversion functions" which provide specific rules for converting your type to another type, and single-arg constructors are used in conversions too:

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

这篇关于C ++中的类型转换/铸造混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆