之间有什么区别
(type)value
和
type(value)
在C ++中?
答案 0 :(得分: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);
答案 1 :(得分: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)
不同,但确实显示了这些精确令牌可能意味着什么的一种方式。它声明了一个名为a_var
的无符号类型的变量,并且根本不是强制转换。 (如果您熟悉指向函数或数组的指针,请考虑如何在p
或void (*pf)()
类型中使用int (*pa)[42]
周围的parens。)
(由于这些语句不使用该值而产生警告,并且在一个真正的程序中几乎肯定是一个错误,但一切仍然有效。我只是在做了一切之后没有心去改变它向上。)
答案 2 :(得分:7)
两者都是强制转换时没有区别,但有时'type(value)'不是强制转换。
以下是标准草案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中提到的含糊不清一样 解决方案是考虑任何可能是a的构造 声明宣言。
答案 3 :(得分:1)
在c中没有type (value)
,而在c / c ++中,type (value)
和(type) value
都是允许的。
答案 4 :(得分: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
}