首页 > 代码库 > 初识C++的类
初识C++的类
//Sales_item.h
#ifndef SALESITEM_H#define SALESITEM_H#include <iostream>#include<string>class Sales_item{public: std::istream &input(std::istream & in); std::ostream & output(std::ostream & out)const; double avg_price() const; bool same_isbn(Sales_item& rhs)const; Sales_item add(Sales_item& other); Sales_item::Sales_item() :unit_sale(0), revenue(0){}private: std::string isbn;//isbn号 int unit_sale;//数量 double revenue;//总价};#endif
//Sales_item.cpp#include "Sales_item.h"std::istream& Sales_item::input(std::istream & in){ double price; in >> isbn >> unit_sale >> price; if (in) revenue = unit_sale*price; else { unit_sale = 0; revenue = 0.0; } return in;}std::ostream& Sales_item::output(std::ostream & out)const{ out << isbn << "\t" << unit_sale << "\t" << revenue << "\t" << avg_price(); return out;}double Sales_item::avg_price() const{ if (unit_sale) return revenue / unit_sale; else return 0.0;}bool Sales_item::same_isbn(Sales_item& rhs)const{ return isbn == rhs.isbn;}Sales_item Sales_item::add(Sales_item& other){ unit_sale += other.unit_sale; revenue += other.revenue; return *this;}
//main.cpp#include <iostream>//#include <string>//#include <vector>//#include <cctype>//#include <cstring>//#include <bitset>#include "Sales_item.h"using namespace std;int main(int argc, char **argv){ Sales_item total, trans; cout << "Enter some transaction (ctrl + z to end)" << endl; if (total.input(cin)){//读入第一个交易 while (trans.input(cin)) { if (total.same_isbn(trans)) total.add(trans); else { total.output(cout); total = trans; } } //输出最后一个交易 total.output(cout) << endl; } else { cout << "No data!" << endl; return -1; } cout << endl; system("pause"); return 0;}
初识C++的类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。