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

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


当前回答

我不知道你怎么会错过这个,这是非常基本的。这是初始化成员变量或基类构造函数的语法。它既适用于普通的旧数据类型,也适用于类对象。

其他回答

它是构造函数的初始化列表。而不是默认构造x、y和z,然后将参数中接收到的值分配给它们,这些成员将立即用这些值初始化。对于浮动来说,这似乎不是特别有用,但是对于构造成本很高的自定义类来说,这可以节省很多时间。

在这个线程中还没有提到:从c++ 11开始,成员初始化器列表可以使用list-initialization(又名list-initialization)。“统一初始化”,“带括号初始化”):

Foo(int num): bar{num} {}

它与其他上下文中的列表初始化具有相同的语义。

这就是构造函数初始化。这是在类构造函数中初始化成员的正确方法,因为它可以防止调用默认构造函数。

考虑以下两个例子:

// Example 1
Foo(Bar b)
{
   bar = b;
}

// Example 2
Foo(Bar b)
   : bar(b)
{
}

例1:

Bar bar;  // default constructor
bar = b;  // assignment

例2:

Bar bar(b) // copy constructor

这都是效率问题。

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

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