设计模式观后(c++还原之四 开闭原则 )

本文介绍了一个使用C++实现的图书商店示例程序,通过继承和多态展示了如何为不同类型的书籍设置价格折扣策略。该程序定义了抽象基类IBook及其实现类NoveBook,并新增了OffNovelBook类来实现特定条件下的折扣。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// Desinger.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <list>
using std::cout;
using std::list;
using std::string;

//开闭原则 
class IBook {
public:
	//获取书名
	virtual string GetName() {return "";}
	//书售价
	virtual int GetPrice() {return 0;}
	//作者
	virtual string GetAuthor() {return "";}
};

class NoveBook : public IBook {
private:
	string	m_strName;
	int		m_nPrice;
	string  m_strAuthor;

public:
	NoveBook(string _name, int _price, string _author)
		: m_strName(_name)
		, m_nPrice(_price)
		, m_strAuthor(_author)
	{}

	virtual string GetAuthor() {
		return m_strAuthor;
	}
	virtual string GetName() {
		return m_strName;
	}
	virtual int GetPrice() {
		return m_nPrice;
	}
};

//然后作者要添加一个降价书本的模块
class OffNovelBook : public NoveBook {
public:
	OffNovelBook(string _name, int _price, string _author)
		: NoveBook(_name, _price, _author) {
	}

	virtual int GetPrice() {
		int selfprice = static_cast<NoveBook>(*this).GetPrice();
		int offPrice = 0;
		if (selfprice > 4000) {
			offPrice = selfprice*90/100;
		} else {
			offPrice = selfprice*80/100;
		}

		return offPrice;
	}
};

//作者代码有没写,我就自己写了
class BookStore {
private:
	static list<IBook*> m_booklist;
	static void Store();
public:
	static void main();
};
list<IBook*> BookStore::m_booklist;
void BookStore::Store() {
	m_booklist.push_back(new OffNovelBook("天龙八部", 3200, "金庸"));
	m_booklist.push_back(new OffNovelBook("巴黎圣母院", 5600, "雨果"));
	m_booklist.push_back(new OffNovelBook("悲惨世界", 4300, "雨果"));
}
void BookStore::main() {
	Store();
	for (list<IBook*>::iterator i = m_booklist.begin();
		i != m_booklist.end(); i++) {
			cout << (*i)->GetName() << ":"
				<< (*i)->GetAuthor() << ":"
				<< (*i)->GetPrice();
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	BookStore::main();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值