题目:
定义一个类Book, 用来描述新书, 具有以下功能:
- 查看当前价格
- 查看当前的书号
定义一个类SellBook, 用来表示促销的书籍, 要求继承自Book类
具有以下功能:
- 查看当前折扣
- 设置当前折扣
- 查看当前的促销价格
代码实现:
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;
}