栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

深入探讨C++父类子类中虚函数的应用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

深入探讨C++父类子类中虚函数的应用

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

1.父类Father.h:
复制代码 代码如下:
#pragma once
class Father
{
public:
 Father(void);
 virtual ~Father(void);
 virtual int getCount();
public:
 int count;
};

Father.cpp
复制代码 代码如下:
#include "StdAfx.h"
#include "Father.h"
#include
using namespace std;
Father::Father(void)
{
 count = 1;
 cout<<"Father is called. count = "<}
Father::~Father(void)
{
 cout<<"~Father is called."<}
int Father::getCount()
{
 cout<<"Father::getCount() count = "< return count;
}

2.子类Child.h:
复制代码 代码如下:
#pragma once
#include "father.h"
class Child :
 public Father
{
public:
 Child(void);
 virtual ~Child(void);
 virtual int getCount();
 int getAge();
public:
 int age;
};

Child.cpp
复制代码 代码如下:
#include "StdAfx.h"
#include "Child.h"
#include
using namespace std;
Child::Child(void)
{
 count = 2;
 age = 20;
 cout<<"Child is called. count = "<}
int Child::getCount()
{
 cout<<"Child::getCount() count = "< return count;
}
int Child::getAge()
{
 cout<<"Child::getAge() age = "< return age;
}

3.测试类Test.cpp
复制代码 代码如下:
#include "stdafx.h"
#include 
#include
#include "Child.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 Father *father1 = new Father();
 cout<<"father1 count = "<getCount()< delete father1;
 cout<<"************** father1 end *****************"< Father *father2 = new Child();
 cout<<"father2 count = "<getCount()< delete father2;
 cout<<"************** father2 end *****************"< Child *child = new Child();
 cout<<"child count = "<getCount()< cout<<"child age = "<getAge()< delete child;
 cout<<"************** child end *****************"< getchar();
 return 0;
}

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 *****************
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/66536.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号