在构造函数中调用类成员的构造函数 [英] calling constructor of a class member in constructor

查看:409
本文介绍了在构造函数中调用类成员的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can I call constructor of a member in my Class's constructor?

让我说如果我有成员 bar MClass 中,类类型为 foo 的>。我可以在MClass的构造函数中调用bar的构造函数吗?如果不是,那我该如何初始化我的会员栏?

let say If I have a member bar of class type foo in my class MClass. Can I call constructor of bar in MClass's constructor? If not, then how can I initialize my member bar?

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

It is a problem of initializing members in composition(aggregation).

推荐答案

是的,当然可以!这就是构造函数初始化器列表的用途。这是一项基本功能,您需要初始化没有默认构造函数的成员以及常量和引用:

Yes, certainly you can! That's what the constructor initializer list is for. This is an essential feature that you require to initialize members that don't have default constructors, as well as constants and references:

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) { }
  //                      ^^^^^^^^^^^^^^^^^^^
};

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

You further need the initializer list to specify a non-default constructor for base classes in derived class constructors.

这篇关于在构造函数中调用类成员的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆