C++类基础代码

来源:互联网 发布:oracle sql语句面试题 编辑:程序博客网 时间:2024/05/22 03:39
#include <string>using namespace std;#pragma onceclass Sale_items{    friend Sale_items add(const Sale_items&,const Sale_items&);    friend ostream &print(ostream&,const Sale_items&);    friend istream &read(istream&,Sale_items &);public:    //Sale_items()=default;  VS2012不支持该语法    Sale_items(void);    Sale_items(const string &s):bookNo(s) {}    Sale_items(const string &s,unsigned n,double p):bookNo(s),units_sold(n),revenue(p*n){}    //Sale_items(string str,unsigned us,double re);    ~Sale_items(void);    string isbn() const    {        return this->bookNo;    }    Sale_items &combine(const Sale_items&);    double avg_price() const;private:    string  bookNo;    unsigned units_sold;    double revenue;};Sale_items add(const Sale_items&,const Sale_items&);ostream &print(ostream&,const Sale_items&);istream &read(istream&,Sale_items &);#include "stdafx.h"#include "Sale_items.h"Sale_items::Sale_items(void){}/*Sale_items::Sale_items(string str,unsigned us,double re){    this->bookNo = str;    this->revenue = re;    this->units_sold = us;}*/Sale_items::~Sale_items(void){}Sale_items & Sale_items::combine(const Sale_items &si){    this->units_sold +=si.units_sold;    this->revenue +=si.revenue;    return *this;}double  Sale_items::avg_price() const{    if(units_sold)    {    return  this->revenue/this->units_sold;    }    else    {        return 0;    }}istream &read(istream &is,Sale_items &item){    double price=0;    is>>item.bookNo>>item.units_sold>>price;    item.revenue = price*item.units_sold;    return is;}ostream &print(ostream &os,const Sale_items &item){    os<<item.isbn()<<" "<<item.units_sold<<" "<<item.revenue<<" "<<item.avg_price();    return os;}Sale_items add(const Sale_items &lhs,const Sale_items &rhs){    Sale_items sum = lhs;    sum.combine(rhs);    return sum;}#pragma once#include "targetver.h"#include <iostream>#include <stdio.h>#include <tchar.h>#include "Sale_items.h"#include "stdafx.h"using namespace std;int _tmain(int argc, _TCHAR* argv[]){    Sale_items total;    cout<<total.isbn()<<endl;    Sale_items *si = new Sale_items("Hello",5,5.0);    Sale_items si1("C++ Primer");    cout<<si->avg_price()<<endl;    return 0;}
0 0