简体   繁体   English

C ++类变量和默认构造

[英]c++ class variables and default construction

class ClassB
{
    int option;

public:
    ClassB(void){} //without the default constructor, the example does not compile.
    ClassB(int option)
    {
        this->option = option;
    }
};

class ClassA
{
    ClassB objB; //initialize objB using default constructor. When does this actually occur?

public:
    ClassA(int option)
    {
        objB = ClassB(option); //initialize objB again using another constructor.
    }
};

int main(void)
{
    ClassA objA (2);

    return 0;
}

I'm new to c++ (coming from c#), and i'm a bit confused about how class variables are initialized. 我是c ++的新手(来自c#),并且对如何初始化类变量有些困惑。 In the above example, ClassA declares a class object of type ClassB, stored by value. 在上面的示例中,ClassA声明了一个ClassB类型的类对象,按值存储。 In order to do this, ClassB must have a default constructor, which implies that ClassA first creates a ClassB using the default constructor. 为此,ClassB必须具有默认构造函数,这意味着ClassA首先使用默认构造函数创建ClassB。 But ClassA never uses this default objB because it's immediately overwritten in ClassA's constructor. 但是ClassA从未使用此默认objB,因为它会立即在ClassA的构造函数中被覆盖。

So my question: Is objB actually initialized twice? 所以我的问题是:objB实际上被初始化了两次吗?

If so, isn't that an unnecessary step? 如果是这样,那不是不必要的步骤吗? Would it be faster to declare objB as a pointer? 将objB声明为指针会更快吗?

If not, why does ClassB need to have a default constructor? 如果没有,为什么ClassB需要一个默认的构造函数?

The reason for this is that you are not initializing the objB data member, but assigning to it after it has been default constructed. 这样做的原因是您没有初始化objB数据成员,而是在默认构造它之后对其进行分配

ClassA(int option)
{
  // By the time you get here, objB has already been constructed
  // This requires that ClassB be default constructable.

    objB = ClassB(option); // this is an assignment, not an initialization
}

To initialize it, use the constructor member initialization list: 要初始化它,请使用构造函数成员初始化列表:

ClassA(int option) : objB(option) {}

This initializes objB with the right constructor, and does not require ClassB to be default constructable. 这将使用正确的构造函数初始化objB ,并且不需要ClassB是默认可构造的。 Note that the same applies to ClassB , whose constructors should be 请注意,这同样适用于ClassB ,其构造函数应为

ClassB() : option() {} // initializes option with value 0
ClassB(int option) : option(option) {}

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

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