问题
代码
Sales_item.h
#include<iostream>
#include<string>
class Sales_item
{public:Sales_item(){};Sales_item(std::string insid, int num, double price);friend std::istream& operator>>(std::istream& is, Sales_item& item);friend std::ostream& operator<<(std::ostream& os, const Sales_item& item);friend Sales_item operator+(const Sales_item& item1,const Sales_item& item2);private:std::string insid_;int num_;double price_;
};
Sales_item.cpp
#include"Sales_item.h"Sales_item::Sales_item(std::string insid, int num, double price)
:insid_(insid)
,num_(num)
,price_(price)
{
}std::istream& operator>>(std::istream& is, Sales_item& item)
{is>>item.insid_>>item.num_>>item.price_;return is;
}std::ostream& operator<<(std::ostream& os,const Sales_item& item)
{os<< item.insid_<<" "<<item.num_<<" "<<item.num_*item.price_<<" "<<item.price_;return os;
}Sales_item operator+(const Sales_item& item1,const Sales_item& item2)
{if(item1.insid_==item2.insid_){return Sales_item(item1.insid_, item1.num_+item2.num_, (item1.num_*item1.price_+item2.num_*item2.price_)/(item1.num_+item2.num_));}else{return item1;}
}
prog1.cc
#include<iostream>
#include "Sales_item.h"
int main()
{Sales_item item1,item2;std::cin>>item1>>item2;std::cout<<"相加结果:"<<std::endl;std::cout<<item1+item2<<std::endl;return 0;
}
运行
g++ prog1.cc Sales_item.cpp -o prog
[root@localhost myPractice]# ./prog
0-201-78345-X 3 20.00
0-201-78345-X 2 25.00
相加结果:
0-201-78345-X 5 110 22
知识点
友元函数可以访问其所属类的私有成员,但不是类的成员函数。友元函数没有隐含的this指针,因此不能直接访问类的非静态成员变量.
思考:
1.不使用友元函数怎么实现?
2.哪些运算符不能重载?