C ++私有区域中的实例变量初始化

时间:2017-05-04 06:59:12

标签: c++ object constructor

在A班中,counter b(5);无效。

while counter a;(默认构造函数的调用)有效。

为什么呢?是否无法为实例变量调用参数化构造函数?

class counter {
private:
  int value;
public:
  counter() { this->value = 0; }
  counter(int value) { this->value = value; }
};

class A {
  private:
    // works
    counter a;
    // works (since C++11)
    int x = 5; 
    // doesn't work
    counter b(5);
};

int main()
{
// works
counter myCounter;
// works as well
counter mySecondCounter(5);
return 0;
}

4 个答案:

答案 0 :(得分:3)

如果允许counter b(5);在技术上声明一个名为b的函数,该函数按值返回counter个对象,并获取一个整数的参数。< / p>

虽然这很可能不是编码人员的意图,但这是不允许的原因。

在Bjarne中关于 In-Class Initializers 的此规则的话:

我们可以在类声明中为非静态数据成员指定初始值设定项。例如:

class A {
  public:
    int a {7};
    int b = 77;
};

由于与解析和名称查找相关的非常模糊的技术原因,{}=初始值设定项     符号可用于课堂成员初始值设定项,但 ()表示法不能。

答案 1 :(得分:1)

有可能。变化

counter b(5);

counter b = counter(5);

在构造函数初始化列表中初始化可能更为优雅。

class A {
private:
    A() : b(5) {}

    counter a;
    int x = 5;
    counter b;
};

答案 2 :(得分:1)

您有四种选择:

class A {
private:
    counter C1{5};

    // Works, only with single parameter constructors
    counter C2 = 5;

    // Works, with any number of parameters
    counter C3 = counter(5);

    counter C4;

    // Constructor initializer list, works with any number of parameters
    A() : C4(5) {}
};

答案 3 :(得分:1)

在C ++中,这不是使用默认值初始化成员的正确语法。

有两种方法可以解决它:

1.use operator =

counter b = counter(5);

2.使用带有初始化列表的构造函数

A() : a(),b(5) {}
相关问题