C++ 58 之 计算器案例

虚函数,vitual function

C++动态多态性是通过虚函数来实现的,虚函数允许子类(派生类)重新定义父类(基类)成员函数,而子类(派生类)重新定义父类(基类)虚函数的做法称为覆盖(override),或者称为重写。

对于特定的函数进行动态绑定,c++要求在基类中声明这个函数的时候使用virtual关键字,动态绑定也就对virtual函数起作用.

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

class Cal {
public:
    int m_a;
    int m_b;
    virtual int getRes(){
        return 0;
    }
};

// 加法  子类要重写父类的虚函数
class Add : public Cal {
public:
    virtual int getRes(){
        return m_a + m_b;
    }
};

// 减法
class Sub : public Cal {
public:
    int getRes(){
        return m_a - m_b;
    }
};

int main()
{
    // 多态可以改善代码的可读性和组织性,同时也可以让程序具有可扩展性
    // 动态多态产生条件:
    // 1.要有继承关系
    // 2.父类中有虚函数、子类要重写父类的虚函数
    // 3.父类的指针或引用指向子类的对象
    
    // 加法:写法1 指针 
    // Cal* c1 = new Add;  // 函数名一样,但对象不一样,就执行不同对象里的函数 多态
    // c1->m_a = 1;
    // c1->m_b = 2;
    // cout << c1->getRes() << endl;
    // delete c1;
    // c1 = NULL;

    // 减法:写法1 指针
    // Cal* c1 = new Sub;
    // c1->m_a = 1;
    // c1->m_b = 2;
    // cout << c1->getRes() << endl;
    // delete c1;
    // c1 = NULL;

    // 加法:写法2 引用
    Add a1;
    Cal& c1 = a1;
    c1.m_a = 1;
    c1.m_b = 2;
    cout << c1.getRes() << endl;

    // 减法:写法2 引用
    Sub s1;
    Cal& c2 = s1;
    c2.m_a = 1;
    c2.m_b = 2;
    cout << c2.getRes() << endl;
    
    return 0;
}
相关推荐
肆忆_15 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星18 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc