在类组合中调用参数化构造函数
Calling the parameterized constructor in class composition
组合有点像继承,但不是继承超类,而是子类的数据成员。
在这种情况下,无论何时创建子类的对象,如何调用超类的参数化构造函数(我知道我们不能在这里使用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的构造函数中的参数。
相关文章:
- C++:使用运算符 = 调用多参数构造函数
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 好奇的混合与可变参数构造函数
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 为什么我们需要创建一个单参数构造函数来使用临时的无名称对象
- 在可变参数构造函数中初始化常量数组
- C++ 显式多参数构造函数歧义
- 零一参数构造函数
- 可变参数构造函数中的 SFINAE
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 可变参数类模板和可变参数构造函数
- 确保模板参数类型与其可变参数构造函数的类型匹配
- C++默认参数构造函数与内联初始化优先级
- 如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?
- 自动存储中没有无参数构造函数的类对象和异常
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 如何在C++中调用无参数构造函数
- 在 c++ 中具有多个参数构造函数的模板类存在问题
- 可变参数构造函数优先于用户提供的移动构造函数,除非默认
- 如何从可变参数构造函数参数构造任何对象?