码迷,mamicode.com
首页 > 编程语言 > 详细

【C++ Primer 第七章】 定义数据抽象类

时间:2018-04-20 22:08:33      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:+=   else   class   bool   this   iostream   c++ prime   price   include   

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 第七章】 定义数据抽象类

标签:+=   else   class   bool   this   iostream   c++ prime   price   include   

原文地址:https://www.cnblogs.com/sunbines/p/8893552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!