首页 > 其他 > 详细

实现:多态计算机类

时间:2019-11-16 11:37:51      阅读:86      评论:0      收藏:0      [点我收藏+]

这里一共写了两种实现,普通的写法,还有一种的多态的写法,进行比较

自己感觉多大的区别其实就是:解耦性

两种方法都没有错,主要在后期的维护中,普通写法修改一个地方,可能就会导致牵一发而动全身的后果,而多态的写法,体现了解耦的思想,更方法单一进行修改

多态写法:

代码如下

#include<iostream>
#include<string>

using namespace std;

class Dt_jsj {
public:

    virtual int to_js() {
        return 0;
    } //定义了一个虚函数,那么相应的也会生成虚拟指针和虚拟表

public:
    int a;
    int b;
};

class Add_jsj:public Dt_jsj{
public:
    int to_js() {
        return a + b;
    }
};


class Sub_jsj :public Dt_jsj{
public:
    int to_js() {
        return a - b;
    }
};


void test01() {
    Dt_jsj  * jsj = new Add_jsj; //生成一个Dt_jsj的指针 指向new出来的内存地址,相当于引用 Dt_jsj & jsj    
    jsj->a = 100;
    jsj->b = 100;
    cout << jsj->to_js() << endl;
}


int main() {
    test01();
    system("pause");
    return 0;
}

普通写法:

代码如下

#include<iostream>
#include<string>

using namespace std;

//普通计算机类的实现
class Common_jsj {
public:
    Common_jsj(int a, int b) {
        this->a = a;
        this->b = b;
    }

    //void to_js(string fuh) { //发现switch对string不支持那就只能换成if语句了
    //  switch (fuh) {
    //  case '+':
    //      return this->a + this->b;
    //  case '-':
    //      return this->a - this->b;
    //  case '*':
    //      return this->a * this->b;
    //  }
    //}
    int to_js(string fuh) {
        if (fuh == "+") {
            return this->a + this->b;
        }
        else if (fuh == "-") {
            return this->a - this->b;
        }
        else if (fuh == "*") {
            return this->a * this->b;
        }
    }

public:
    int a;
    int b;

};

void test01() {
    Common_jsj j1(100, 100);
    cout << j1.to_js("+") << endl;
}
int main() {
    test01();
    system("pause");
    return 0;
}

实现:多态计算机类

原文:https://www.cnblogs.com/zpchcbd/p/11871029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!