/*
* virtualVar.cpp
*
* Created on: 2016年8月24日
* Author: zroad
*/
#include<iostream>
using namespace std;
//一。虚函数的概念:
/*
* 1、虚函数的定义:类Base中加了Virtual关键字的函数就是虚拟函数(例如函数print),
* 2、多态的实现:于是在Base的派生类Derived中就可以通过重写虚拟函数来实现对基类虚拟函数的覆盖。
* 当基类Base的指针point指向派生类Derived的对象时,对point的print函数的调用实际上是调用了Derived的print函数而不是Base的print函数。
* 这是面向对象中的多态性的体现。
*/
class Base {
public:
Base() {
cout << "Class Base is created!" << endl;
}
virtual void print() {
cout << "Base class is used!" << endl;
}
~Base() {
cout << "Base class is deleted!" << endl;
}
};
class Derived : public Base {
public:
Derived() {
cout << "Class Derived is created!" << endl;
}
void print() {
cout << "Derived class is used!" << endl;
}
~Derived() {
cout << "Derived class is deleted!" << endl;
}
};
//二、纯虚函数的概念:
//纯虚函数是在基类中声明的虚函数,它在基类中没有定义,但要求任何派生类都要定义自己的实现方法。
class PureVirtualClass {
public:
PureVirtualClass() {
cout << "PureVirtualClass is created!" << endl;
}
virtual void printPure();
~PureVirtualClass() {
cout << "PureVirtualClass is deleted!" << endl;
}
};
class DerivedPureVirtualClass : public PureVirtualClass {
public:
DerivedPureVirtualClass() {
cout << "DerivedPureVirtualClass is created!" << endl;
}
void printPure() {
cout << "PureVirtualClass is tested!" << endl;
}
~DerivedPureVirtualClass() {
cout << "Bye,bye!" << endl;
}
};
int main() {
/*运行结构钢:
* Class Base is created!
Class Derived is created!
Derived class is used!
Base class is deleted!
*
*/
//调用顺序:
/*
1.成员方法不需要初始化,因为这些全部是指针。
2.初始化派生类的静态字段。
3.初始化派生类的非静态字段。
4.初始化基类的静态字段。
5.初始化基类的非静态字段。
6.调用基类的构造函数。
7.调用派生类的构造函数。
*/
//多态的实现,基类指针调用派生类的方法
Base *a = new Derived();
a -> print();
delete a;
//纯虚函数的调用
DerivedPureVirtualClass *d = new DerivedPureVirtualClass();
d -> printPure();
delete d;
return 0;
}
虚函数及纯虚函数
最新推荐文章于 2024-03-05 13:33:01 发布