虚函数
定义: 基类中指向派生类的函数,简单的说就是virtual 修饰的函数
作用: 当基类的指针指向派生类的对象时能调用派生类新增的成员
- 实现机制: 基类中多了一个虚函数表 指针数组
同一类族中不同类的对象,对同一函数调用做出不同的响应:这就是由虚函数实现的动态多态性
函数重载处理的是同一层次上的同名函数问题,属横向重载 静态关联
虚函数处理的是派生层次上的同名函数问题, 属纵向重载 动态关联
确定具体的调用对象称为关联
动态关联 : 当虚函数是被指针调用的时候,由于在编译阶段无法确定指针指向的是哪个对象,故为动态关联
实现机制图解:
代码解释:
#include <iostream>
using namespace std;
class Basic
{
public:
Basic(){
n = 2;
}
virtual void f(){
cout << "in Basic::f() ..." << endl;
}
void g(){
cout << "in Basic::g() ..." << endl;
}
protected:
int n;
};
int main()
{
cout << "sizeof(Basic): " << sizeof(Basic) << endl;
Basic b;
b.f();
//给函数指针类型 定义 别名
typedef void (*FP)();
//使用函数指针类型 定义 (函数指针)变量
FP pf;
pf = (FP)*(int *)*(int *)(&b); //
// pf = (FP)*(int *)(&b); //*(int *)(&b) 指向虚函数表(指针数组)需要缩短他的标示内存: (int *)*(int *)(&b)
void (Basic::*p)() = &Basic::g;//成员函数的指针写法及调用方式
(b.*p).g();
cout << "pf: " << pf << endl;
//通过函数指针调用 函数
pf();
return 0;
}
使用实例:
#include <iostream>
using namespace std;
class Circle
{
protected:
float radius;
float x;
float y;
public:
Circle(float f_x=0, float f_u=0, float f_r=0);
float area() const;
};
Circle::Circle(float f_x, float f_y, float f_r){
x = f_x;
y = f_y;
radius = f_r;
}
float Circle::area() const{
cout << "circle::area...\n";
return 3.14*radius*radius;
}
class Cylinder : public Circle
{
protected:
float hight;
public:
Cylinder(float x=0, float y=0, float r=0, float h=0);
float area() const;
};
Cylinder::Cylinder(float x, float y, float r, float h):Circle(x,y,r){
hight = h;
}
float Cylinder::area() const{
cout << "cylinder::area...\n";
return 2*Circle::area() + 2*3.14*radius;
}
int main()
{
Cylinder c(3.3,3.4,5,8);
Circle *c1 = &c;
cout << c1->area() << endl;
}
纯虚函数 与 抽象类
纯虚函数:形如以下的函数 无实际意义 目的:给派生类留一个函数名
void fun() const = 0;
抽象类即不能实例化的类,特征:如果一个类中含有纯虚函数即为抽象类