#include <iostream>
struct Foo
{
Foo(int d) : x(d) {}
int x;
};
int main()
{
double x = 3.14;
Foo f( int(x) );
std::cout << f.x << std::endl;
return 0;
}
当我编译这段代码时,出现以下错误:
[Error] request for member 'x' in 'f', which is of non-class type 'Foo(int)'
假设在 int main
中我删除了 Foo f(int(x))
中的 int
。
我的意思是如果我这样写:
Foo f(x);
代码编译正确,输出为 3。
那么如果我们输入像 Foo f(int(x)) 这样的参数来调用构造函数会发生什么?
最佳答案
Foo f(int(x));
这不是类型转换,而是函数声明 - 函数 f
这需要 int
称为 x
并返回 Foo
.
语法允许在声明中的标识符周围使用一组(理论上是无限的)括号。和你写的一样
Foo f(int x);
或
Foo f( int (((x))) );
正如您已经知道的那样,您不需要进行转换,因为 double
之间的转换和 int
是隐含的。但如果你真的想要,你可以说 static_cast<int>(x)
相反或
Foo f((int (x)));
// ^ ^
这使它成为一个表达式而不是声明。
关于c++ - 类型转换构造函数参数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17299697/