#include
using namespace std;
class Base {
int x;
public:
Base(int n = 0) : x(n)
{
cout << x;
}
Base(int m, int n) : x(n)
{
cout << x;
}
int getX() const {}
};
class Delive :public Base {
int y;
public:
Delive(int m, int n) : y(m), Base(n)
{
cout << y;
}
Delive(int m) : y(m)
{
cout << y;
}
};
int main(int argc, char* argv[]) {
Delive d1(3);
return 0;
}
如上述代码所示,结果是03 ,朋友的解释是 0是调用父类构造函数打印出的,3是子类构造函数打印出的。但是我认为不应该有0,调用父类构造函数也应该是3,结果应该是33。于是我做了以下测试
#include
using namespace std;
class Base {
int x;
public:
Base(int n = 0) : x(n)
{
cout << x;
}
Base(int m, int n) : x(n)
{
cout << x;
}
int getX() const {}
};
int main(int argc, char* argv[]) {
Base d1(3);
return 0;
}
这里我删除了子类,直接创建父类对象,打印是3,所以不能理解,为什么在有子类的时候,创建子类对象,父类构造函数会打印0.
调用父类构造函数也应该是3===为什麽呢?父类构造函数输出的是x,x怎么会成为3呢?永远也不会是3啊
Delive d1(3);
调用的是Delive::Delive(int)
构造函数
Delive(int m) : y(m) // 这里没有指定Base的构造函数,因此调用Base()构造函数,而Base::Base(int n=0)缺省值是0,故打印0
{
cout << y; //然后打印y,即3
}