Lig*_*XXV 1 c++ constructor derived-class default-parameters
我写了这个小程序来测试我的理解。我很难理解的是构造函数没有被继承,但是类B能够调用类A的构造函数!
#include <iostream>
using namespace std;
class A {
public:
A(int x = 2) { //Constructor A
num = x;
}
int getNum() {
return num;
}
protected:
int num;
};
class B: public A { //Constructor B
public:
B() {
A(5);
}
};
int main() {
A a(3); //create obj a with num = 3
B b; //create obj b
cout << a.getNum() << endl;
cout << b.getNum() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出为:
3
2
Run Code Online (Sandbox Code Playgroud)
构造函数A的调用到底做了什么?它没有使用传递的参数来初始化对象b的编号!
此外,如果我从类A的构造函数中删除默认值,则会出现编译错误:
no matching function for call to 'A::A()'
Run Code Online (Sandbox Code Playgroud)
那么,这里到底发生了什么?
我知道正确的方法是:
class B: public A { //Constructor B
public:
B() : A(5) {
}
};
Run Code Online (Sandbox Code Playgroud)
给出输出:
3
5
Run Code Online (Sandbox Code Playgroud)
但这只是出于理解的目的。
让我们看一下B构造函数:
B() {
A(5);
}
Run Code Online (Sandbox Code Playgroud)
在这里,您实际上两次 “调用”了A构造函数。一次作为构造的一部分(在其中调用“默认” 构造函数),一次在构造函数主体内创建一个临时对象。BAB
顺序如下
B 构造函数称为A作为B对象初始化的一部分调用的默认构造函数B输入构造函数的主体A5作为创建临时对象的一部分调用的非默认构造函数(带有arguments )B构造函数的主体退出| 归档时间: |
|
| 查看次数: |
1714 次 |
| 最近记录: |