子类调用父类的构造函数方式一览

首先要了解子类调用构造函数过程:父类构造函数–>子类构造函数

1.父类有默认构造函数,子类未显示调用时,子类自动调用父类的默认构造函数;

#include <iostream>
using namespace std;

class Father
{
public:
	Father()
	{
		cout << "父类默认构造函数!\n";
	}
};

class Children : public Father
{
public:
	Children()
	{
		cout << "子类构造函数!\n" << endl;
	}
};

int main(int argc, char** argv)
{
	Children rec;

	return 0;
}

2.父类有默认构造函数,子类显示调用时,子类自动调用父类的默认构造函数;

#include <iostream>
using namespace std;

class Father
{
public:
	Father()
	{
		cout << "父类默认构造函数!\n";
	}
};

class Children : public Father
{
public:
	Children() : Father()
	{
		cout << "子类构造函数!\n" << endl;
	}
};

int main(int argc, char** argv)
{
	Children rec;

	return 0;
}

3.父类没有默认构造函数,子类显示调用时,子类会调用系统为父类生成的默认构造函数;

#include <iostream>
using namespace std;

class Father
{
public:
// 	Father()
// 	{
// 		cout << "父类默认构造函数!\n";
// 	}
};

class Children : public Father
{
public:
	Children() : Father()
	{
		cout << "子类构造函数!\n" << endl;
	}
};

int main(int argc, char** argv)
{
	Children rec;

	return 0;
}

4.父类没有默认构造函数,子类未显示调用时,子类会调用系统为父类生成的默认构造函数;

#include <iostream>
using namespace std;

class Father
{
public:
// 	Father()
// 	{
// 		cout << "父类默认构造函数!\n";
// 	}
};

class Children : public Father
{
public:
	Children()// : Father()
	{
		cout << "子类构造函数!\n" << endl;
	}
};

int main(int argc, char** argv)
{
	Children rec;

	return 0;
}

5.父类有带参数的构造函数,也有默认构造函数,子类未显示调用父类构造函数时,子类会调用父类默认构造函数;

#include <iostream>
using namespace std;

class Father
{
public:
	Father()
	{
		cout << "父类默认构造函数!\n";
	}
	Father(int nNum)
	{
		cout << "父类传参构造函数!\n";
	}
};

class Children : public Father
{
public:
	Children()
	{
		cout << "子类构造函数!\n" << endl;
	}
};

int main(int argc, char** argv)
{
	Children rec;

	return 0;
}

6.父类有带参数的构造函数,也有默认构造函数,子类显示调用父类一种构造函数时,子类会调用父类该种构造函数;

#include <iostream>
using namespace std;

class Father
{
public:
	Father()
	{
		cout << "父类默认构造函数!\n";
	}
	Father(int nNum)
	{
		cout << "父类传参构造函数!\n";
	}
};

class Children : public Father
{
public:
	Children() : Father(1)
	{
		cout << "子类构造函数!\n" << endl;
	}
};

int main(int argc, char** argv)
{
	Children rec;

	return 0;
}

错误方式:
父类仅写了带参数的构造函数,没写不带参数的默认构造函数时,而子类又没有显示调用父类构造函数时,编译失败。因为父类写了构造函数,系统就不会为父类生成默认构造函数,子类想调用父类的默认构造函数时找不到;

#include <iostream>
using namespace std;

class Father
{
public:
// 	Father()
// 	{
// 		cout << "父类默认构造函数!\n";
// 	}
	Father(int nNum)
	{
		cout << "父类传参构造函数!\n";
	}
};

class Children : public Father
{
public:
	Children()// : Father()
	{
		cout << "子类构造函数!\n" << endl;
	}
};

int main(int argc, char** argv)
{
	Children rec;

	return 0;
}

如果觉得子类调用父类构造函数情况太多,不好记忆,那么每次写子类构造函数时最好显示调用父类构造函数!

  • 11
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值