最近我看到了这样一个例子:
#include <iostream>
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}
这个奇怪的bar(num)是什么意思?它似乎初始化了成员变量,但我以前从未见过这种语法。它看起来像一个函数/构造函数调用,但int?这对我来说毫无意义。也许有人能启发我。顺便问一下,还有没有其他像这样深奥的语言特性,你在普通的c++书中找不到?
另一个已经向您解释过,您观察到的语法称为“构造函数初始化列表”。此语法允许自定义初始化类的基子对象和成员子对象(而不是允许它们默认初始化或保持未初始化)。
I just want to note that the syntax that, as you said, "looks like a constructor call", is not necessarily a constructor call. In C++ language the () syntax is just one standard form of initialization syntax. It is interpreted differently for different types. For class types with user-defined constructor it means one thing (it is indeed a constructor call), for class types without user-defined constructor it means another thing (so called value initialization ) for empty ()) and for non-class types it again means something different (since non-class types have no constructors).
在本例中,数据成员的类型为int。Int不是类类型,所以它没有构造函数。对于int类型,此语法仅意味着“用num值初始化bar”,仅此而已。它就是这样直接完成的,不涉及构造函数,因为int不是类类型,因此它不能有任何构造函数。
另一个已经向您解释过,您观察到的语法称为“构造函数初始化列表”。此语法允许自定义初始化类的基子对象和成员子对象(而不是允许它们默认初始化或保持未初始化)。
I just want to note that the syntax that, as you said, "looks like a constructor call", is not necessarily a constructor call. In C++ language the () syntax is just one standard form of initialization syntax. It is interpreted differently for different types. For class types with user-defined constructor it means one thing (it is indeed a constructor call), for class types without user-defined constructor it means another thing (so called value initialization ) for empty ()) and for non-class types it again means something different (since non-class types have no constructors).
在本例中,数据成员的类型为int。Int不是类类型,所以它没有构造函数。对于int类型,此语法仅意味着“用num值初始化bar”,仅此而已。它就是这样直接完成的,不涉及构造函数,因为int不是类类型,因此它不能有任何构造函数。