1. 程式人生 > >【C++ Primer 第七章】 定義數據抽象類

【C++ Primer 第七章】 定義數據抽象類

IE color != AS count prime 編號 unit ons

Sales_data類

頭文件Sales_data.h

/*
 *   頭文件:Sales_data.h
 */
#include<iostream>
#include<string>

class Sales_data
{
    friend std::istream& operator>> (std::istream &in, Sales_data &rhs);
    friend std::ostream& operator<< (std::ostream &os, const
Sales_data &rhs); friend bool operator== (const Sales_data &rhs, const Sales_data &yhs); friend bool operator!= (const Sales_data &rhs, const Sales_data &yhs); public: Sales_data() = default; Sales_data(const std::string &book) : bookNo(book) {} Sales_data(std::istream
&is) { is >> *this; } Sales_data& operator+= (const Sales_data &rhs); std::string isbn() const { return this->bookNo; } private: std::string bookNo; //書籍編號 unsigned units_sold = 0; //銷售量 double sellingprice = 0.0; //原始價格 double saleprice = 0.0
; //銷售價格 double discount = 0.0; //折扣 }; std::istream& operator>> (std::istream &in, Sales_data &rhs) { in >> rhs.bookNo >> rhs.units_sold >> rhs.sellingprice >> rhs.saleprice; if (rhs.sellingprice != 0) rhs.discount = rhs.saleprice / rhs.sellingprice; else rhs = Sales_data(); return in; } std::ostream& operator<< (std::ostream &os, const Sales_data &rhs) { os << rhs.bookNo << rhs.units_sold << rhs.sellingprice << rhs.saleprice << rhs.discount; return os; } bool operator== (const Sales_data &rhs, const Sales_data &yhs) { if(rhs.bookNo == yhs.bookNo && rhs.units_sold == yhs.units_sold && rhs.sellingprice == yhs.sellingprice && rhs.discount == yhs.discount) return true; else return false; } bool operator!= (const Sales_data & rhs, const Sales_data & yhs) { return false; } bool operator!= (const Sales_data &rhs, const Sales_data &yhs) { return !(rhs == yhs); } Sales_data& Sales_data::operator+= (const Sales_data &rhs) { units_sold += rhs.units_sold; saleprice = (units_sold * saleprice + rhs.units_sold * rhs.saleprice) / (units_sold + rhs.units_sold); if (sellingprice != 0) discount = saleprice / sellingprice; return *this; }

【C++ Primer 第七章】 定義數據抽象類