2009-10-30 171 views

回答

50

没有区别;按照标准(§5.2.3):

一个简单类型说明符(7.1.5),后面跟着一个带括号的表达式列表,根据表达式列表构造一个指定类型的值。如果表达式列表是单个表达式,那么类型转换表达式与相应的表达式(5.4)是等价的(在定义中,如果定义的话)。

由于问题指定了type(value)(type)value之间的差异,所以绝对没有区别。

当且仅当您处理以逗号分隔的列表的值可能会有差异。在这种情况下:

如果表达式列表指定比单个值时,类型应与适当声明的构造(8.5,12.1)的一类,并且表达T(X1,X2,...)相当于声明T t(x1,x2,...);对于一些发明的临时变量t,其结果是t的值作为右值。

正如Troubadour指出的那样,某些名称的类型type(value)版本根本无法编译。例如:

char *a = (char *)string; 

将编译,但:

char *a = char *(string); 

不会。相同类型使用不同的名称(例如,用typedef创建)可以工作,虽然:

typedef char *char_ptr; 

char *a = char_ptr(string); 
+0

仅适用于内置类型。 – Troubadour 2009-10-30 21:35:33

+7

恩,不,没有区别。 +1 – 2009-10-30 21:37:18

+2

嗯,也许:)但是untypedef'ed指针类型呢? – Troubadour 2009-10-30 21:44:16

13

没有区别; C++标准(1998和2003版)明确了这一点。尝试下面的程序,确保你使用了一个兼容的编译器,比如免费预览http://comeaucomputing.com/tryitout/

#include <cstdlib> 
#include <string> 
int main() { 
    int('A'); (int) 'A'; // obvious 
    (std::string) "abc"; // not so obvious 
    unsigned(a_var) = 3; // see note below 
    (long const&) a_var; // const or refs, which T(v) can't do 
    return EXIT_SUCCESS; 
} 

注:unsigned(a_var)是不同的,但确实显示单程那些确切的令牌可能意味着别的东西。它声明了一个类型为unsigned的变量a_var,根本不是变体。 (如果你熟悉函数指针或数组,考虑如何在一个类型像void (*pf)()int (*pa)[42]使用周围p一个括号。)

(警告产生,因为这些语句不使用的价值和在一个真正的程序中,几乎可以肯定是一个错误,但一切仍然有效,我只是没有心在一切排列后改变它。)

+0

不错的代码格式,是那个意图吗? – squelart 2010-03-05 23:42:14

+2

@squelart:一开始不是,但一旦接近,我就开始工作了,只是没有心情去改变它,以摆脱警告。 – 2010-03-06 04:25:07

6

当两者都是强制转换时没有区别,但有时'类型(价值)'不是演员。

下面是从N3242标准草案,第8.2.1节的例子:

struct S 
{ 
    S(int); 
}; 

void foo(double a) 
{ 
    S w(int(a)); // function declaration 
    S y((int)a); // object declaration 
} 

在这种情况下 'INT的(a)' 不是铸造因为 'A' 是不是一个值,它是一个参数名称被冗余括号包围。该文件指出

从函数式 演员和6.8中提到的也可以发生在一个声明的上下文 声明之间的相似性引起的歧义。在这种情况下,选择范围在函数 声明与一个冗余的括号参数 名称和一个具有函数样式类型的对象声明作为 初始值设定项。正如6.8中提到的含糊之处一样, 决议是考虑任何可能是声明声明的构造。

1

在C没有type (value),而在C/C++两者type (value)(type) value和允许。

0

为了说明用C你的选择++(只有一个具有安全检查)

#include<boost/numeric/conversion/cast.hpp> 

using std::cout; 
using std::endl; 
int main(){ 

    float smallf = 100.1; 

    cout << (int)smallf << endl; // outputs 100 // c cast 
    cout << int(smallf) << endl; // outputs 100 // c++ constructor = c cast 

    cout << static_cast<int>(smallf) << endl; // outputs 100 
// cout << static_cast<int&>(smallf) << endl; // not allowed 
    cout << reinterpret_cast<int&>(smallf) << endl; // outputs 1120416563 
    cout << boost::numeric_cast<int>(smallf) << endl; // outputs 100 

    float bigf = 1.23e12; 

    cout << (int)bigf << endl; // outputs -2147483648 
    cout << int(bigf) << endl; // outputs -2147483648 

    cout << static_cast<int>(bigf) << endl; // outputs -2147483648 
// cout << static_cast<int&>(bigf) << endl; // not allowed 
    cout << reinterpret_cast<int&>(bigf) << endl; // outputs 1401893083 
    cout << boost::numeric_cast<int>(bigf) << endl; // throws bad numeric conversion 
} 
相关问题