C++-类-多态1:多态基本概念

多态是面向对象程序设计语言中数据抽象和继承之外的第三个基本特征。

多态性(polymorphism)提供接口具体实现之间的另一层隔离,从而将”what”和”how”分离开来。

多态性改善了代码的可读性和组织性,同时也使创建的程序具有可扩展性,项目不仅在最初创建时期可以扩展,而且当项目在需要有新的功能时也能扩展。

c++支持编译时多态(静态多态)和运行时多态(动态多态),运算符重载和函数重载就是编译时多态,而派生类和虚函数实现运行时多态。

静态多态和动态多态的区别就是函数地址是早绑定(静态联编)还是晚绑定(动态联编)。

如果函数的调用,在编译阶段就可以确定函数的调用地址,并产生代码,就是静态多态(编译时多态),就是说地址是早绑定的。

而如果函数的调用地址不能编译不能在编译期间确定,而需要在运行时才能决定,这这就属于晚绑定(动态多态,运行时多态)。

//计算器

class Caculator{

public:

    void setA(int a){

        this->mA = a;

    }

    void setB(int b){

        this->mB = b;

    }

    void setOperator(string oper){

        this->mOperator = oper;

    }

    int getResult(){

       

        if (this->mOperator == "+"){

            return mA + mB;

        }

        else if (this->mOperator == "-"){

            return mA - mB;

        }

        else if (this->mOperator == "*"){

            return mA * mB;

        }

        else if (this->mOperator == "/"){

            return mA / mB;

        }

    }

private:

    int mA;

    int mB;

    string mOperator;

};

//这种程序不利于扩展,维护困难,如果修改功能或者扩展功能需要在源代码基础上修改

//面向对象程序设计一个基本原则:开闭原则(对修改关闭,对扩展开放)

//抽象基类

class AbstractCaculator{

public:

    void setA(int a){

        this->mA = a;

    }

    virtual void setB(int b){

        this->mB = b;

    }

    virtual int getResult() = 0;

protected:

    int mA;

    int mB;

    string mOperator;

};

//加法计算器

class PlusCaculator : public AbstractCaculator{

public:

    virtual int getResult(){

        return mA + mB;

    }

};

//减法计算器

class MinusCaculator : public AbstractCaculator{

public:

    virtual int getResult(){

        return mA - mB;

    }

};

//乘法计算器

class MultipliesCaculator : public AbstractCaculator{

public:

    virtual int getResult(){

        return mA * mB;

    }

};

void DoBussiness(AbstractCaculator* caculator){

    int a = 10;

    int b = 20;

    caculator->setA(a);

    caculator->setB(b);

    cout << "计算结果:" << caculator->getResult() << endl;

    delete caculator;

}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值