简体   繁体   English

在其他类构造函数中使用参数化构造函数

[英]use parameterized constructor in other classes constructor

I fear that this is a very basic question, however, I was not able to solve it yet. 我担心这是一个非常基本的问题,然而,我还没能解决它。

I have a class A 我有一个class A

// classA.h
...

class ClassA {
    public:
        ClassA();
        ClassA(int foo);
    private:
        int _foo;

    ...

}

// classA.cpp

ClassA::ClassA() {
    _foo = 0;
}

ClassA::ClassA(int foo) {
    _foo = foo;
}

...

A second class B uses an instance of class A in the constructor: 第二个class B在构造函数中使用class A的实例:

// classB.h
...

#include "classA.h"

#define bar 5

class ClassB {
    public:
        ClassB();
    private:
        ClassA _objectA;

    ...

}

// classB.cpp

ClassB::ClassB() {
    _objectA = ClassA(bar);
}

...

Note that the default constructor of class A is never used. 请注意,从不使用class A的默认构造函数。 In fact in my real world use case it would not even make sense to use any kind of a default constructor as _foo has to be dynamically assigned. 事实上,在我的真实世界用例中,使用任何类型的默认构造函数都没有意义,因为必须动态分配_foo

However, if I remove the default constructor, the compiler returns an error: 但是,如果我删除默认构造函数,编译器将返回错误:

no matching function for call to 'ClassA::ClassA()' 调用'ClassA :: ClassA()'没有匹配函数

Is there a way to use an instance of class A as an object in class B without defining a default constructor for class A ? 有没有办法在class B使用class A的实例作为对象而不为class A定义默认构造函数? How would this be done? 怎么做?

The default constructor of ClassA is used. 使用ClassA的默认构造函数。 ClassB 's _objectA is initialized with it and then you assign ClassA(bar) to it. 使用它初始化ClassB_objectA然后为其分配ClassA(bar)

You can solve your problem by using constructor initializer lists : 您可以使用构造函数初始化列表来解决您的问题:

ClassB::ClassB() : _objectA(bar)
{}

Just write 写吧

ClassB::ClassB() :  _objectA(bar)
{
}

The problem is that when the body of the constructor of the ClassB is executed the data member _objectA is already constructed and inside the body there is used the copy assignment operator 问题是当执行ClassB的构造函数的主体时,数据成员_objectA已经构造并且在主体内部使用了复制赋值运算符

ClassB::ClassB() {
    _objectA = ClassA(bar);
   ^^^^^^^^^^^^^^^^^^^^^^^^
}

Thus you can remove the default constructor of the ClassA . 因此,您可以删除ClassA的默认构造函数。

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

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