use parameterized constructor in other classes constructor

爱⌒轻易说出口 提交于 2019-12-12 14:07:35

问题


I fear that this is a very basic question, however, I was not able to solve it yet.

I have 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:

// 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. 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.

However, if I remove the default constructor, the compiler returns an error:

no matching function for call to '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? How would this be done?


回答1:


The default constructor of ClassA is used. ClassB's _objectA is initialized with it and then you assign ClassA(bar) to it.

You can solve your problem by using constructor initializer lists:

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



回答2:


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::ClassB() {
    _objectA = ClassA(bar);
   ^^^^^^^^^^^^^^^^^^^^^^^^
}

Thus you can remove the default constructor of the ClassA.



来源:https://stackoverflow.com/questions/40665414/use-parameterized-constructor-in-other-classes-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!