C++多态案例---计算器类

【C++】多态案例— —计算器类 阅读详情

我们要实现的是分别利用普通写法和多态去实现一个能让两个数进行运算的计算器类 

从而比较多态相比普通写法的优势,在实际的c++开发中是非常提倡利用多态去设计程序架构!

先是普通写法的:

#include <iostream>
using namespace std;

class Calculator
{

public:
     int  docalculator(string oper)
    {
        if(oper=="+")
        {
            return m_num1+m_num2;
        }
        else if(oper=="-")
        {
            return m_num1-m_num2;
        }
        else if(oper=="*")
        {
            return m_num1*m_num2;
        }
    }
    int m_num1;
    int m_num2;

};

void test01()
{
    Calculator  c;
    c.m_num1=10;
    c.m_num2=10;
    cout<<c.m_num1<<"+"<<c.m_num2<<"= "<<c.docalculator("+")<<endl;
    cout<<c.m_num1<<"-"<<c.m_num2<<"= "<<c.docalculator("-")<<endl;
    cout<<c.m_num1<<"*"<<c.m_num2<<"= "<<c.docalculator("*")<<endl;
}
int main()
{
    test01();
    system("pause");
    return 0;
}

普通的写法,没能很好的体现开闭原则,因为如果想扩展新的功能则需要修改类里的源码,而在实际开发中提倡开闭原则,对扩展开放,对修改关闭。

下面我们来看看利用多态的写法:

#include <iostream>
using namespace std;
//先创建一个基类
class Abstractcalculate
{
public:
    virtual int  docalculate()
    {
        return 0;
    }
    int m_num1;
    int m_num2;

};

//下面一一创建自己需要的
//加法类
class  Addcalculate:public Abstractcalculate
{
    public:
    virtual int  docalculate()
    {
        return m_num1+m_num2;
    }
};

//减法类
class  Subcalculate:public Abstractcalculate
{
    public:
    virtual int  docalculate()
    {
        return m_num1-m_num2;
    }
};

//乘法类
class  Mulcalculate:public Abstractcalculate
{
    public:
    virtual int  docalculate()
    {
        return m_num1*m_num2;
    }
};

void test02()
{
    //实现加法,多态使用条件是父类的指针或对象指向子类,这次我们用指针
    Abstractcalculate  *abc=new Addcalculate; //创建一个父类的指针abc去指向新开辟的addcalculate类的空间
    abc->m_num1=100;
    abc->m_num2=100;
    cout<<abc->m_num1<<"+"<< abc->m_num2<<"="<<abc->docalculate()<<endl;
    //此时自然会执行加法类的函数
    delete abc;   //由于是在堆区开辟的一片空间,用完了了要手动释放
    //
    abc=new Subcalculate;  
    //指针指向的空间被删除了,但是指针还在,而且就是Abstractcalculate类型的
    abc->m_num1=100;
    abc->m_num2=100;
    cout<<abc->m_num1<<"-"<< abc->m_num2<<"="<<abc->docalculate()<<endl;
    delete abc;
    abc=new Mulcalculate;
    abc->m_num1=100;
    abc->m_num2=100;
    cout<<abc->m_num1<<"*"<< abc->m_num2<<"="<<abc->docalculate()<<endl;
    delete abc;
}

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

可以感受到多态的好处:
1、组织结构清晰
2、可读性强(以后的开发中,我们可能写代码的时候都没有读代码多,因为一个项目往往是多个人一起做的,所以我们就需要去大量阅读别人的代码,此时如果一个人的代码你一看就读懂了,要知道不是你厉害,大多数时候是写代码的人厉害,因为他能够写的通俗易懂让你看懂)
3、对于前期和后期的拓展和维护性高  很好的体现了开闭原则!

通过此案例,希望大家能切实体会到多态带来的好处,在以后的学习中多多使用多态!
 

C++ 实现一个简单的计算器 类 一个简单的计算器类(类型),要求: (1) 从键盘读入算式。 (2) 可以进行加、减、乘、除运算。 (3) 运算要有优先级。 (4) 用户可以按任何的运算符出现顺序进行输入。 (5) 不限定用户输入的计算式的长度。 (6) 可以带有括号()。 (7) 有排错功能,当用户输入错误的算式时提示用户。 立即下载

相关推荐

机器学习【学校智慧食堂及其应用】

本文主要介绍机器学习【智慧食堂及其应用】

qq_201729558 2571

C++类实现多项式——加减乘运算

一、创建类Polynml 在多项式类Polynml的内部,分别由函数变量,构造函数,析构函数和成员函数组成;另外还有重载运算符:①重载加法(+),②重载减法(-),③重载乘法(*)。 注意多项式的每一项是用二维数组来构成,每个数组的第一维表示系数,第二维表示指数。(例如 2x^4 ;2为系数,4为指数) 二、代码实现 #include<iostream......

qq_42442875的博客 1万+

PTGui使用教程

PTGui使用教程为啥使用ptgui开始使用ptgui 为啥使用ptgui ptgui是一个全景拼接软件,在海思hi3559上做视频拼接的时候,需要拼接参数,这是就需要使用到ptgui,这里可以在该网站下下载ptgui:下载地址 开始使用ptgui 第一步,加载图片,我这里添加了三幅图 然后添加控制点(可以先多对准几次图像,这样会自动生成一些控制点,但是不保证准确),建议控制点不要太密集 点开镜头设置,勾选以下几个选项以及配置好镜头类型,如下图 点开优化器,在高级界面中配置如下参数,最后点

what_wrong的博客 1万+

c++ 计数器类自增

Problem Description 设计一个计数器类Counter,它只有一个用于计数的数据成员num。 实现计数器的前自增、后自增运算。 //你的代码将被嵌在这里 int main() { int n; cin >> n; Counter c1(n); cout << c1++; cout << ++c1; return 0; } Input Description 输入计数器初始值n。 Sample Input 3 Sample Output 3 5 #inclu

dimrhyme的博客 3208

1.28寸圆屏LCD驱动开发:GC9A01与RT-Thread嵌入式实现

圆形TFT-LCD是一种面向可穿戴、IoT终端的紧凑型人机交互显示技术,其核心在于SPI/QSPI接口时序控制与GRAM内存映射原理。通过驱动芯片(如GC9A01)完成电源管理、伽马校正和MADCTL方向配置,可实现低功耗、高刷新率的图形渲染。该技术显著提升嵌入式设备的UI表现力与空间利用率,在智能手环、传感器节点、微型HMI等资源受限场景中具备突出工程价值。本文围绕1.28寸圆屏LCD模块,详解硬件接口规范、RT-Thread下QSPI驱动架构及Bresenham算法优化实践。

weixin_42599908的博客 158

MAX30102心率血氧传感器:从原理到实践的可穿戴健康监测方案

本文深入解析MAX30102心率血氧传感器的工作原理及在可穿戴健康监测中的实践应用。通过反射式光电容积脉搏波(PPG)技术,该传感器能精准测量心率和血氧饱和度,具备低功耗、高抗干扰等优势。文章详细介绍了信号处理算法、硬件连接技巧及创新应用场景,为开发者提供全面的解决方案。

weixin_29184371的博客 283

c++精解和程序设计第十章

无

m0_72647241的博客 1371

HCIP-Cloud Service DevOps Engineer V2.0 华为认证云服务 DevOps高级工程师 章节测试题+结课测试题(模拟考试题)汇总

本文为HCIP-Cloud Service DevOps Engineer V2.0 华为认证云服务DevOps高级工程师 在线课程中所有章节测试以及结课测试(HCIP-Cloud Service DevOps Engineer模拟考试)习题和答案

gaogao0305的博客 2267

C++计算器实现 ——(完整功能实现、设计分析)

基于标准C++的计算器实现。 一、需求实现 1、实现功能: 支持运算符:+, - , *, /, %(百分号), ^(幂次方), | |(绝对值),!(阶乘)。其他符号:( ) [ ] { } 支持数据类型:正负数、小数。 2、实现方法 符号优先级处理方法:符号等级制 运算表达式处理方法:后缀表达式法 后缀表达式转换及计算辅助方法:符号栈、数字栈

demo_yo的博客 5万+

akamai3简单分析

akamai流程的简单分析

记录一些web逆向的过程 916

如何调用 DBMS_DISKGROUP 对 ASM 文件进行随机读取

该篇博客介绍了如何通过 Java 调用 DBMS_DISKGROUP 读写 Oracle ASM 共享存储文件,并提供了 Java Demo。并测试出 DBMS_DISKGROUP 存在性能瓶颈。

我要出家当道士 1179

【C++】多态实现简单计算机类

C++多态实现简单计算机类 普通写法实现计算器类 //普通写法 #include<iostream> #include<string> using namespace std; class Calculator { public: int getResult(string oper) { if (oper == "+") { return m_Num1 + m_Num2; } else if (oper == "-") { return m_

lsz20000813的博客 812

QGis二次开发 —— 5、基于qgis开发多种在线地图预览,并加入经纬度坐标显示等(附:源码)

QGis二次开发 —— 5、基于qgis开发多种在线地图预览,并加入经纬度坐标显示等(附:源码

369

C++ 多态案例 计算器类

【代码】C++ 多态案例 计算器类。

qq_62313069的博客 201

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C++_核心编程_多态案例一-计算器类

本文展示了利用多态技术实现计算器类的案例。通过定义抽象基类AbstractCalculator和具体运算子类(加法、减法、乘法),演示了多态在代码组织、可读性和扩展性方面的优势。每个子类重写getResult()方法实现特定运算,主函数通过基类指针调用不同运算,体现了"一个接口,多种实现"的多态特性。相比普通写法,多态实现更易维护和扩展,只需添加新子类即可支持更多运算,而无需修改现有代码。案例突出了多态在面向对象程序设计中的核心价值。

leijinquan01的博客 233

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

C++学习记录--b站黑马程序员视频——55 类和对象-多态-案例1-计算器类

55 类和对象-多态-案例1-计算器类。

m0_59179752的博客 199

C++多态案例-设计计算器类

多态是面向对象的三大特性之一多态分为两类静态多态和动态多态的区别动态多态必须满足的条件。

weixin_40933653的博客 1088

C++多态案例(一)-计算器类

/多态优点:代码组织结构清晰(哪里出问题直接定位),可读性强,利于前期和后期的扩展(想添加什么功能直接添加相关类)以及维护(哪里出问题直接定位,一个功能出问题不影响其他功能)多态优点:代码组织结构清晰(哪里出问题直接定位),可读性强,利于前期和后期的扩展(想添加什么功能直接添加相关类)以及维护(哪里出问题直接定位,一个功能出问题不影响其他功能)分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类。//如果要提供新的运算,需要修改源码。delete abc;多态案例一-计算器类。

m0_72677702的博客 345

【C++多态案例:计算器类】

分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类(简单的加减乘除)

lzz_233的博客 297

c++ 多态案例----计算器类

c++ 多态案例----计算器类

wangbaba_1的博客 752

[C++ 核心编程]笔记 4.7.2 多态案例--计算器类

多态的优点: 1. 代码组织结构清晰 2. 可读性强 3. 利于前期和后期的扩展以及维护 在真实的开发中 提倡 开闭原则 开闭原则: 对扩展进行开放, 对修改进行关闭 总结: C++开发提倡利用多态设计程序架构,因为多态优点很多

Alex的博客 374

11.7.2重学C++之【多态案例--计算器类】

#include<stdlib.h> #include<iostream> #include<string> using namespace std; /* 4.7.2 多态案例--计算器类 案例描述: 分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类 多态的优点: 代码组织结构清晰 可读性强 利于前期和后期的扩展.

yubaby 380

C++入门学习:多态案例--计算器类

多态方法的简单实例

Miki Makimura 的博客 203

c++多态写法和普通写法的优劣对比(借用一个计算器类的实际案例来说明)

案例:一个计算器类,实现加减乘操作。 1.普通写法 #include<iostream> #include<string> using namespace std; class calculate { int m_a; int m_b; public: calculate(int a, int b) { m_a = a; m_b = b; } int function_calculate(string str) { if (str == "+") r

admin的博客 377

c++ day13(1) 多态,计算器类案例(new 创建对象)

1.基本概念 多态分为两类 静态多态:函数重载和运算符重载属于静态多态,复用函数 动态多态:派生类和虚函数实现运行时多态 静态多态和动态多态区别 静态多态的函数地址早已绑定——编译阶段确定函数地址 动态多态的函数地址晚绑定——运行阶段确定函数地址 动态多态条件 继承关系 子类和父类有函数重写(即函数同名) 动态多态使用 父类的指针或引用 指向子类对象 void dospeak(school &s) //父类的指针或引用指向子类的对象 { s.index(); } ...

dfhg54的博客 641

【b站黑马程序员C++视频学习笔记-多态案例一-计算器类】

多态案例之计算器

qq_42622072的博客 466
上一篇: c++多态的基本概念
下一篇: C++虚函数,纯虚函数和抽象类
从一的
博客等级 码龄5年 1995粉丝 213原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值