最近我看到了这样一个例子:

#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++书中找不到?


当前回答

这是一个初始化列表。它将在运行构造函数体之前初始化成员。 考虑

class Foo {
 public:
   string str;
   Foo(string &p)
   {
      str = p;
   };
 };

vs

class Foo {
public:
  string str;
  Foo(string &p): str(p) {};
};

在第一个例子中,str将由它的无参数构造函数初始化

string();

在Foo构造函数体之前。在foo构造函数内部,

string& operator=( const string& s );

将在'str'上调用,就像你执行str = p;

而在第二个例子中,str将直接由 调用它的构造函数

string( const string& s );

用'p'作为参数。

其他回答

它是一个成员初始化列表。你可以在任何好的c++书籍中找到有关它的信息。

在大多数情况下,您应该初始化成员初始化列表中的所有成员对象(但是,请注意FAQ条目末尾列出的例外)。

常见问题解答的要点是,

在其他条件相同的情况下,如果使用初始化列表而不是赋值,代码将运行得更快。

这是一个初始化列表。它将在运行构造函数体之前初始化成员。 考虑

class Foo {
 public:
   string str;
   Foo(string &p)
   {
      str = p;
   };
 };

vs

class Foo {
public:
  string str;
  Foo(string &p): str(p) {};
};

在第一个例子中,str将由它的无参数构造函数初始化

string();

在Foo构造函数体之前。在foo构造函数内部,

string& operator=( const string& s );

将在'str'上调用,就像你执行str = p;

而在第二个例子中,str将直接由 调用它的构造函数

string( const string& s );

用'p'作为参数。

还有一个“好处”

如果成员变量类型不支持空初始化,或者它是一个引用(不能被空初始化),那么你别无选择,只能提供一个初始化列表

另一个已经向您解释过,您观察到的语法称为“构造函数初始化列表”。此语法允许自定义初始化类的基子对象和成员子对象(而不是允许它们默认初始化或保持未初始化)。

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不是类类型,因此它不能有任何构造函数。

你是正确的,这确实是一种初始化成员变量的方法。我不确定这样做有什么好处,除了清楚地表示它是一个初始化。在代码中使用“bar=num”可能更容易被移动、删除或误解。