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

C++虚函数和纯虚函数

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

C++虚函数和纯虚函数

C++虚函数和纯虚函数

虚函数是C++实现多态的重要工具。

考虑一种情况,现在有形状这个基类,给基类有一个area()函数,如下

class Shape {
	int area(){...}
}

在其派生类中重写这个方法

class A : public Shape{
	int area(){...}
}
class B : public Shape{
	int area(){...}
}

int main(){
    Shape* shape;
    A a;
    B b;
    
    shape = &a;
    shape.area();
    
    shape = &b;
    shape.area();
    
    return 0;
}

此时两个shape.area()到底调用了哪一个函数?

结果是shape.area() 调用了基类的area方法。

如果要调用派生类的函数,需要使用虚函数,如下:

#include 
using namespace std;

class Shape {
protected:
    int width, height;
public:
    Shape(int a = 0, int b = 0)
    {
        width = a;
        height = b;
    }

    // 虚函数
    virtual int area()
    {
        cout << "Parent class area :" << endl;
        return 0;
    }
    // 纯虚函数
    virtual int Perimeter() = 0;

    void test() {
        cout << "test" << endl;
    }
};


class  A :public Shape
{
public:
    A(int a = 0, int b = 0) :Shape(a, b) {}
    // 虚函数
    int area()
    {
        cout << "A class area :" << endl;
        return 0;
    }

    // 纯虚函数
    int Perimeter() {
        return 1;
    }

    void test() {
        cout << "A" << endl;
    }
};


class  B :public Shape
{
public:
    B(int a = 0, int b = 0) :Shape(a, b) {}

    // 虚函数
    int area()
    {
        cout << "B class area :" << endl;
        return 0;
    }

    // 纯虚函数
    int Perimeter() {
        return 2;
    }

    void test() {
        cout << "B" << endl;
    }
};


int main() {

    A a(1, 2);
    B b(1, 2);

    a.area();
    a.Perimeter();


    b.area();
    b.Perimeter();

    Shape* shape;
    shape = &a;
    shape->area();
    shape->Perimeter();
    shape->test();

    shape = &b;
    shape->area();
    shape->Perimeter();
    shape->test();

    return 0;
}


这是为什么?

首先:案例一中的现象叫 静态多态(或者静态链接、早绑定)

这意味着在程序编译阶段shape->area()就确定函数的入口是基类的area()函数。

案例二中真正实现了多态,virtual关键字告诉编译器不要在编译阶段绑定shape->area(),而是在执行阶段选择函数入口。

纯虚函数

纯虚函数在基类不实现,即只定义了函数,而没有具体实现。在其派生类中必须实现。(纯虚函数类似与Java中的Interface)而且纯虚函数有“=0”的后缀

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/348338.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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