调用不带参数的构造函数有效,带参数则无效。为什么?

Calling a constructor with no parameters works, with a parameter doesn't. Why?

我有一个class定义如下:

class Foo {

  private:
    boolean feature;

  public:
    Foo(boolean feature) : feature(feature) {}

  // ...
};

我正在尝试构建一个实例,作为另一个 class:

的私有 属性
class Bar {

  private:
    Foo foo(true);

    // ...
  };

这行不通。我在声明的那一行得到了 expected identifier before numeric constant。当我简单地从 Foo 的构造函数定义中删除参数并请求 Foo foo; 时,它起作用了。

为什么?

如何定义和声明采用布尔参数的 Foo 实例?

您不能在 class 成员声明中使用该初始化语法;您只能使用 {}= 初始化成员。以下应该有效(假设支持 C++11 或更高版本):

Foo foo{true};
Foo foo = Foo(true);

C++11 之前的方法是:

class Bar {
  public:
    Bar() : foo(true){} //initialization
  private:
    Foo foo; //no parameter
};

奖金:

class Bar {
  private:
    Foo foo(); //<- This is a function declaration for a function
               //named foo that takes no parameters returning a Foo.
               //There is no Foo object declared here!
};