读完C++ Primer 第4版 第一章后 实现的Sale_item类

内容概要: C++ primer 类实现

header file(Sale_item.h):

#ifndef SALES_ITEM_H
#define SALES_ITEM_H

#include
class Sales_item
 {
     public:
         Sales_item();
         virtual ~Sales_item();
         bool same_isbn(Sales_item& s);
     protected:
     private:
         std::string isbn;
         unsigned int units_sold;
         double revenue;
         double avg_price;

     friend std::istream& operator>>(std::istream& in, Sales_item& s);
     friend std::ostream& operator<<(std::ostream& out, Sales_item& s);
     friend Sales_item& operator+(Sales_item & s1, Sales_item& s2);
 };

#endif // SALES_ITEM_H

   

实现(Sale_item.cpp):

#include "Sales_item.h"

Sales_item::Sales_item()
 {
     //ctor
 }

Sales_item::~Sales_item()
 {
     //dtor
 }

bool Sales_item::same_isbn(Sales_item& s)
 {
     if (isbn == s.isbn)
      {
          return true;
      }
     else return false;
 }

std::istream& operator>>(std::istream& in, Sales_item& s)
 {
   in>>s.isbn>>s.units_sold>>s.avg_price;
   s.revenue = s.units_sold*s.avg_price;
   return in;
 }

std::ostream& operator<<(std::ostream& out, Sales_item& s)
 {
    out<<s.isbn<<" "<<s.units_sold<<" "<<s.revenue<<" "<<s.avg_price;
  return out;
 }

Sales_item& operator+(Sales_item & s1, Sales_item& s2)
 {
     if(s1.isbn != s2.isbn)
     {
         //do something
     }
     s1.units_sold = s1.units_sold + s2.units_sold;
     s1.revenue = s1.revenue + s2.revenue;
     s1.avg_price = s1.revenue/s1.units_sold;

    return s1;
}

 

====================================================

C++ 学习, 坚持,每天进步一点点!

以前只有C基础, 通过上面的类,会使用基本的操作符重载

注意点: 操作符重载, 即可以选择成员函数重载,也可非成员函数(一般是友元, 为了访问类的Private 成员); 当用成员函数重载时,参数比正常的要少一个,因为成员函数有一个隐含的this指针,指向该类的一个对象。 

————————————————————————————————

个人原创内容, 转载请注明来源 huqijun.org !

本文最初发布在CSDN:https://blog.csdn.net/xiaoyaohuqijun/article/details/47762393

© 2019, Qijun Hu. All rights reserved. 版权所有, 转载请注明出处和链接!

Leave a Reply

Your email address will not be published. Required fields are marked *