简体   繁体   English

类默认构造函数中的c ++类

[英]c++ class in a class default constructor

My concern is a default constructor and its initialisation list. 我关心的是默认构造函数及其初始化列表。 In a simple case it's clear, like: 在一个简单的例子中,它很明显,如:

class A
{
  protected:
       double d1;
       //classB obj1; //how to initialize this one in a default constructor?
  public:
       A (double x = 0.0): d1(x){} //constructor
       virtual ~A(void) {};
  //something
}

But how to initialize the object of classB, which has a big amount of members? 但是如何初始化classB的对象,它有大量的成员? Or how in general initialize in default constructor some type that has a big or unknown amount of parameters to be initialized? 或者一般如何在默认构造函数中初始化某些具有大量或未知数量的参数进行初始化的类型?

You could initialize obj1 in member initializer list by calling its default constructor or other constructors 您可以通过调用其默认构造函数或其他构造函数来初始化member initializer list的obj1

class A
{
  protected:
       double d1;
       classB obj1; 
       pthread_mutex_t m_mutex;
  public:
       A (double x = 0.0): d1(x), obj1(), m_mutex(PTHREAD_MUTEX_INITIALIZER) {} 
       virtual ~A(void) {}
       //something
}

if classB has big of members like you described, you may break the rule of class design - one class does one thing . 如果classB拥有像你所描述的那么大的成员,那么你可能会破坏类设计的规则 - one class does one thing只做one class does one thing You might want to break classB into small independent classes. 您可能希望将classB分解为小的独立类。

If you want to explicitly initialize an object, just add it to the constructor initializer list: 如果要显式初始化对象,只需将其添加到构造函数初始化列表中:

struct Foo
{
    Foo(int arg) { ... }
};

struct Bar
{
    Foo foo;

    Bar()
        : foo(123)  // Initialize `foo` with an argument
    { ... }
};

If the member can be initialized by its default constructor, then it doesn't even have to be in the initialization list, because a default constructor doesn't have parameters. 如果成员可以通过其默认构造函数初始化,那么它甚至不必在初始化列表中,因为默认构造函数没有参数。 The default constructor will be called. 将调用默认构造函数。 Primitives don't have default constructors so they have to be in the initialization list if you want to have them initialized. 基元没有默认构造函数,因此如果要初始化它们,它们必须位于初始化列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM