是什么(类型)的类型和值(值)之间的区别?
-
22-07-2019 - |
题
是什么
之间的差(type)value
和
type(value)
在C ++?
解决方案
有任何区别;按照标准(§5.2.3):
后跟带括号表达式列表的简单型说明符(7.1.5)构建体给出的表达式列表中指定的类型的值。如果表达式列表是一个单一表达式,类型转换表达式是等效(在definedness,并且如果在含义定义)到相应的转换表达式(5.4)。
由于议题指定type(value)
和(type)value
之间的差,也绝对没有差别。
当且仅当您正在处理值的逗号分隔的列表的才会有差异。在这种情况下:
如果表达式列表指定比单个值时,类型应与适当声明的构造(8.5,12.1)的一类,并且表达T(X1,X2,...)相当于有效的声明T T [ (X1,X2,...);对于某些发明临时变量t,结果是作为右值t的值。
正如游吟诗人指出的那样,有对于该type(value)
版本根本不会编译类型特定名称。例如:
char *a = (char *)string;
将编译,但:
char *a = char *(string);
不会。相同类型使用不同的名称(例如,用typedef
创建)可以工作,虽然:
typedef char *char_ptr;
char *a = char_ptr(string);
其他提示
有任何区别; 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]
。)
(因为这些语句不使用的值,并在实际的程序会几乎肯定是一个错误警告的生产,但一切仍在工作。我只是没有足够的心脏做一切线后改变它向上。)
有任何差别,当两者都是石膏,但有时“类型(值)”不是铸造。
下面是从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中,提到的歧义 分辨率是考虑任何结构,它也可能会被一 声明的声明。
在C没有type (value)
,而在C / C ++两者type (value)
和(type) value
是允许的。
要说明用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
}