C++父类子类中虚函数的使用

构造函数不能是虚函数,因为在调用构造函数创建对象时,构造函数必须是确定的,所以构造函数不能是虚函数。

析构函数可以是虚函数。

 

1.父类Father.h:

Father.cpp

 

2.子类Child.h:

Child.cpp

3.测试类Test.cpp

4.输出结果:

Father is called. count = 1
Father::getCount() count = 1
father1 count = 1
~Father is called.
************** father1 end *****************

 

Father is called. count = 1
Child is called. count = 2, age = 20
Child::getCount() count = 2
father2 count = 2
~Child is called.
~Father is called.
************** father2 end *****************

 

Father is called. count = 1
Child is called. count = 2, age = 20
Child::getCount() count = 2
child count = 2
Child::getAge() age = 20
child age = 20
~Child is called.
~Father is called.
************** child end *****************

发布了270 篇原创文章 · 获赞 276 · 访问量 379万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览