虚函数

虚函数

  1. 定义: 基类中指向派生类的函数,简单的说就是virtual 修饰的函数

  2. 作用: 当基类的指针指向派生类的对象时能调用派生类新增的成员

  3. 实现机制: 基类中多了一个虚函数表 指针数组

同一类族中不同类的对象,对同一函数调用做出不同的响应:这就是由虚函数实现的动态多态性

函数重载处理的是同一层次上的同名函数问题,属横向重载 静态关联
虚函数处理的是派生层次上的同名函数问题, 属纵向重载 动态关联

确定具体的调用对象称为关联

动态关联 : 当虚函数是被指针调用的时候,由于在编译阶段无法确定指针指向的是哪个对象,故为动态关联


实现机制图解:
这里写图片描述
代码解释:

#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;

抽象类即不能实例化的类,特征:如果一个类中含有纯虚函数即为抽象类

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值