在类组合中调用参数化构造函数

时间:2015-03-19 20:59:04

标签: c++

组合有点像继承,但是超级类不是继承超类,而是子类的数据成员。

在这种情况下,无论何时创建子类的对象,如何调用超类的参数化构造函数(我知道我们不能在这里使用术语sub和super class,但它只是为了清晰起见)。

class A {
    int a;
public:
    A() {
        cout << "\nDefault constructor of A called.\n";
        a = 0;
    }
    A(int x) {
        cout << "\nParameterized constructor of A called.\n";
        a = x;
    }
    int getA() {
        return a;
    }
};

class B {
    A o;
    int b;
public:
    B() {
        cout << "\nDefault constructor of B called.\n";
        b = 0;
    }
    B(int x) {
        cout << "\nParameterized constructor of B called.\n";
        b = x;
    }
    int getB() {
        return b;
    }
}; 

class C {
    int c;
public:
    A o;
    C() {
        cout << "\nDefault constructor of C called.\n";
        c = 0;
    }
    C(int x) {
        cout << "\nParameterized constructor of C called.\n";
        c = x;
    }
    int getC() {
        return c;
    }
}; 

B和C是两种不同版本的构图。如何在其中任何一个中调用A的参数化构造函数。我的意思是,请相应地修改类定义。

2 个答案:

答案 0 :(得分:1)

使用member initializer lists

class C
{
private:
    A a;
    int b;

public:
    C(int x) :
        a(x),  // <- Calls the `A` constructor with an argument
        b(x)   // <- Initializes the `b` member to the value of `x`
    { }
};

答案 1 :(得分:0)

B(int x) : o(x) {
    cout << "\nParameterized constructor of B called.\n";
    b = x;
}

注意使用传递给B的构造函数的参数初始化成员变量o。

相关问题