当A类没有默认构造函数时,在B类中拥有A类

时间:2019-12-03 14:02:32

标签: c++ c++11 visual-c++ c++14 c++17

我有一个A类,该类属于要在B类中使用的库的一部分。如果A类没有默认构造函数,如何将A类作为B类的私有成员? B需要用几个变量初始化,如果可能的话,我想在其他地方初始化它。

class A
{
public:
    A();
    ~A();

private:
    B b;
}; 

2 个答案:

答案 0 :(得分:3)

  

如果A类没有默认构造函数,如何将A类作为B类的私有成员

您只需在构造函数中称其为构造函数

A::A() 
: b( /* args go here */ ) ...
{
}

或者如果您不能提供默认参数,则将其传递给

A::A( /* args for b */ ) 
: b( /* pass args for b through */ ) ...
{
}

答案 1 :(得分:0)

B声明为A类的成员时,可以调用它的非默认构造函数。该代码可以按预期编译并运行,但这是一个非常简单的情况:

#include <iostream>

class B {
public:
    B() = delete; // This ENSURES we don't have a default constructor!
    B(int i, int j) : p{ i }, q{ j } { } // Constructor MUST have two int arguments!
    int p, q;
};

class A {
public:
public:
    A() : {}
    ~A() {}
    void setB(int i, int j) { b.p = i; b.q = j; } // Can be called later
    int getP() { return b.p; }
    int getQ() { return b.q; }
private:
    B b = B(0, 0); // LEGAL declaration of a "B" member: gives default (phoney) args/data
                   // ... which can be set later:e.g. using "setB(18,12)"
//  B bb; // ERROR - attempting to referencea deleted function!
};

int main()
{
    A a; // The "B" member (a.b) will have its "phoney" (default) values
    std::cout << a.getP() << " " << a.getQ() << std::endl;
    //...
    // 'later'...
    a.setB(18,12); //  
    std::cout << a.getP() << " " << a.getQ() << std::endl;
    return 0;
}

随时要求进一步的澄清和/或解释。

相关问题