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

c++ 面向对象程序设计--开闭原则

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

c++ 面向对象程序设计--开闭原则

c++ 面向对象程序设计–开闭原则

在面对对象程序设计中,有很多原则需要我们去学习,在这里用c++简单的演示一下,开闭原则。开闭原则实质就是对扩展开放、修改封闭。等于说,一个系统需要增加新的功能,是在原有的基础上去扩展,而不是修改已有功能的代码。例如下面的计算器小程序,只实现了加法和减法、后续可以扩展乘除等等。(利用多态的思想,使得程序的可扩展性更强)

// 开闭原则.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include 
#include 
#include 

class Calculate
{
public:
	virtual int myCalculate() = 0;
};

// 加法
class Add :public Calculate
{
public:
	Add(int a,int b)
	{
		this->a = a;
		this->b = b;
	}

	virtual int myCalculate()
	{
		return a + b;
	}

private:
	int a;
	int b;
};

// 减法
class Sub:public Calculate
{
private:
	int a;
	int b;

public:
	Sub(int a,int b)
	{
		this->a = a;
		this->b = b;
	}

	virtual int myCalculate()
	{
		return a - b;
	}
};

// 后续可扩展乘法、除法、取模、开根、平方等等。


int main()
{
	Calculate * p = new Add(10,20);
	int mAdd = p->myCalculate();
	std::cout << mAdd << std::endl;
	delete p;

	p = new Sub(10, 2);
	int mSub = p->myCalculate();
	std::cout << mSub << std::endl;
	delete p;
	system("pause");
	return 0;
}


结果:

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

版权所有 (c)2021-2022 wk8.com.cn

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