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

Calling the parameterized constructor in class composition

本文关键字:参数 构造函数 调用 组合      更新时间:2023-10-16

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

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

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的参数化构造函数。我的意思是,请相应地修改类定义。

使用成员初始值设定项列表:

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`
    { }
};
B(int x) : o(x) {
    cout << "nParameterized constructor of B called.n";
    b = x;
}

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