C++父类怎么调用子类中的虚函数

来源:爱站网时间:2021-06-21编辑:网友分享
只要深究过虚函数的人应该都清楚,c++的多态是来自于虚函数表的函数指针覆,而本篇内容中,爱站技术频道小编将教大家C++父类怎么调用子类中的虚函数,对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::~Father(void)
{
 cout }
int Father::getCount()
{
 cout  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::~Child(void)
{
 cout }
int Child::getCount()
{
 cout  return count;
}
int Child::getAge()
{
 cout  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();
 coutgetCount()  delete father1;
 cout  Father *father2 = new Child();
 coutgetCount()  delete father2;
 cout  Child *child = new Child();
 coutgetCount()  coutgetAge()  delete child;
 cout  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 *****************

在以上内容中,爱站技术频道小编已经详细为大家分析了C++父类子类中虚函数的应用,同时,本频道还整理了大量C语言相关内容,想知道的就继续关注吧。

上一篇:C语言中可以用32位int型变量表示单引号括起来的四个字符

下一篇:深入分析关于C++输出指针自增(++)运算

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载