include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int main()
{
struct Sales_Data {
Sales_Data() = default;
Sales_Data(const string &s) :bookNo(s) {}
Sales_Data(const string &s, unsigned n, double p) :bookNo(s), units_sold(n), revenue(n*p) {}
Sales_Data(istream &is);
string isbn() const { return bookNo; }
Sales_Data & combine(const Sales_Data&);
double avg_price() const;
//数据成员
string bookNo;
unsigned units_sold = 0;
double revenue = 0;
};
//在类的外部定义成员函数
double Sales_Data::avg_price()const {
if (units_sold)
return revenue / units_sold;
else
return 0;
}
Sales_Data add(const Sales_Data& data1, const Sales_Data& data2) {
Sales_Data sum = data1;
sum.combine(data2);
return sum;
}
istream& read(istream &is, Sales_Data &item) {
double price = 0;
is >> item.bookNo >> " " >> item.units_sold;
item.revenue = price*units_sold;
return is;
}
ostream& print(ostream &os, Sales_Data &item) {
os << item.bookNo >> " " << item.units_sold << " " << item.revenue;
return os;
}
Sales_Data::Sales_Data(istream &is) {
return read(is, *this);
}
Sales_Data& Sales_Data::combine(const Sales_Data& rhs) {
units_sold += rhs.units_sold;
revenue += rhs.renvenue;
return *this;
}
Sales_Data t1;
t1.Sales_Data("TheCatcherInRye", 3, 20.5);
print(os, t1);
return 0;
}
c++ 不能在函数里面定义函数。