项目十一练习1

题目:

定义一个类Book, 用来描述新书, 具有以下功能:

  1. 查看当前价格
  2. 查看当前的书号

定义一个类SellBook, 用来表示促销的书籍, 要求继承自Book类
具有以下功能:

  1. 查看当前折扣
  2. 设置当前折扣
  3. 查看当前的促销价格

代码实现:

1. Book类

头文件

#pragma once
#include <string>

using namespace std;

class Book
{
public:
	Book();
	Book(float price, const string &bookNo);
	float getPrice() const;
	string getBookNo() const;

protected:
	float price;
	string bookNo;
};

实现方法

#include "Book.h"

Book::Book()
{
	price = 0.0;
	bookNo = "无号";
}

Book::Book(float price, const string & bookNo)
{
	this->price = price;
	this->bookNo = bookNo;
}

float Book::getPrice() const
{
	return price;
}

string Book::getBookNo() const
{
	return bookNo;
}

2. sellBook类

头文件

#pragma once
#include "Book.h"

class SellBook : public Book
{
public:
	SellBook();
	SellBook(float price, const string &bookNo, float discount);
	float getDiscount() const;
	void setDiscount(float preDiscount);
	float getPrice() const;
	string description() const;

private:
	float discount;
};

实现方法

#include <sstream>
#include "SellBook.h"

SellBook::SellBook()
{
	discount = 0.0;
}

SellBook::SellBook(float price, const string & bookNo, float discount): Book(price,bookNo)
{
	this->discount = discount;
}

float SellBook::getDiscount() const
{
	return discount;
}

void SellBook::setDiscount(float preDiscount)
{
	discount = preDiscount;
}

float SellBook::getPrice() const
{
	if (discount ==0) {
		return price;
	}
	else
	{
		return discount * price / 10;
	}
}

string SellBook::description() const
{
	stringstream ret;
	ret << bookNo << "打折为: " << discount << "折 当前价格为: " << getPrice();

	return ret.str();
}

3. 调用

#include <iostream>
#include "SellBook.h"

int main() {
	SellBook primer(100.5,"C++ Primer",0);

	cout << "不打折扣" << endl;
	cout << primer.description() << endl;

	cout << "双十一打折开启" << endl;
	primer.setDiscount(8);
	cout << primer.description() << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值