原始类型没有构造函数已经被反复强调了。例如,当我调用 Foo()
时,此 _bar
未初始化为 0:
class Foo{
int _bar;
};
显然 int()
不是构造函数。但是是它的名字是什么?
在这个例子中,我会说 i
是:(构造的?初始化的?吃错的?)
for(int i{}; i < 13; ++i)
Loki Astari提到 here该技术有某种名称。
编辑以响应 Mike Seymour :
#include <iostream>
using namespace std;
class Foo{
int _bar;
public:
void printBar(){ cout << _bar << endl; }
};
int main()
{
Foo foo;
foo.printBar();
Foo().printBar();
return 0;
}
在 Visual Studio 2013 上运行此代码会产生:
3382592
3382592
有趣的是 gcc 4.8.1 产量:
134514651
0
最佳答案
It's been rehashed over and over that primitive types don't have constructors.
没错。
For example this bar is not initialized to 0 when I call
Foo()
是的。 Foo()
指定值初始化,对于像这样没有用户提供构造函数的类,这意味着它在初始化其成员之前是零初始化的。所以 _bar
以零值结束。 (尽管如评论中所述,一种流行的编译器没有正确地对此类类进行值初始化。)
如果你改用默认初始化,它不会被初始化。你不能用临时的来做到这一点;但是声明的变量 Foo f;
或 new F
的对象将被默认初始化。原始类型的默认初始化什么都不做,给它们留下一个不确定的值。
如果该类有一个用户提供的默认构造函数,并且该构造函数没有专门初始化 _bar
,它也不会被初始化。同样,它将被默认初始化,没有任何效果。
So obviously int() is not a constructor. But what is it's name?
作为表达式,它是 int
类型的值初始化临时值。
从句法上讲,它是“显式类型转换(函数式)”的特例;但是将该术语用于除类型转换之外的任何内容都会相当困惑。
In this example I would say
i
is: (constructed? initialized? fooed?)
已初始化。如果您想更具体,列表初始化(带有空列表)、值初始化或零初始化。
关于c++ - 什么是 int() 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27443532/