在构造函数中调用类成员的构造函数

sha*_*mpa 23 c++ constructor aggregation

我可以在Class的构造函数中调用成员的构造函数吗?

让说,如果我有一个成员bar类类型的foo在我的课MClass.我可以在MClass的构造函数中调用bar的构造函数吗?如果没有,那么我如何初始化我的会员栏?

这是在组合(聚合)中初始化成员的问题.

Ker*_* SB 36

是的,当然可以!这就是构造函数初始化列表的用途.这是一个必不可少的功能,您需要初始化没有默认构造函数的成员,以及常量和引用:

class Foo
{
  Bar x;     // requires Bar::Bar(char) constructor
  const int n;
  double & q;
public:
  Foo(double & a, char b) : x(b), n(42), q(a) { }
  //                      ^^^^^^^^^^^^^^^^^^^
};
Run Code Online (Sandbox Code Playgroud)

您还需要初始化列表来为派生类构造函数中的基类指定非默认构造函数.


eld*_*rge 6

是的你可以:

#include <iostream>

using std::cout;
using std::endl;

class A{
public:
    A(){
        cout << "parameterless" << endl;
    }

    A(const char *str){
        cout << "Parameter is " << str <<endl;
    }
};

class B{
    A _argless;
    A _withArg;

public:
    // note that you need not call argument-less constructor explicitly.
    B(): _withArg("42"){
    }
};

int main(){
    B b;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

parameterless
Parameter is 42
Run Code Online (Sandbox Code Playgroud)

在ideone.com上查看此内容

  • 您对无需显式调用的无参数成员构造函数的评论正是我所寻找的。谢谢! (2认同)