美文网首页
C++之类-1

C++之类-1

作者: Oneshot_fea8 | 来源:发表于2019-02-01 22:09 被阅读0次
#include<iostream>
#include<string>

using namespace std;

class Sales_items
{
public:
    Sales_items(std::string &book, unsigned units, double amount)
        :isbn(book), units_sold(units), revenue(amount)
    {}

    //书的平均价格
    double avg_price() const
    {
        if (units_sold) 
            return revenue / units_sold;
        else
            return 0;

    }

    //判断卖的是否是同样的书
    bool same_isbn(const Sales_items &rhs) const
    {
        return isbn == rhs.isbn;
    }

    void add(const Sales_items &rhs)
    {
        units_sold += rhs.units_sold;
        revenue += rhs.revenue;
    }

private:
    std::string isbn;   //书号
    unsigned units_sold;//销售数量
    double revenue;     //总金额
};

class Person
{
    //成员
public:
    /*Person(const std::string &nm,const std::string &addr)
    {
        name = nm;
        address = addr;
    }*/

    //另外一种方法是利用构造函数的初始化列表对函数成员进行赋值,更加简洁
    Person(const std::string &nm, const std::string &addr) :name(nm), address(addr)
    {

    }
    std::string getName() const//定义成const的原因是该函数只进行读操作,而不改变函数的成员,这样更安全
    {
        //用公有的函数成员操作私有的数据成员
        return name;
    }
    std::string getAdress() const
    {
        return address;
    }

private:
    std::string name;
    std::string address;
};

int main()
{
    Person a("zhangfei","garden street");

    //cout << a.name << "," << a.address;
    cout << a.getName() << "," << a.getAdress() << endl;

    Sales_items x(string("0-399-82477-1"), 2, 20.00);
    Sales_items y(string("0-399-82477-1"), 6, 48.00);
    cout << x.avg_price() << endl;
    cout << y.avg_price() << endl;
    if (x.same_isbn(y))
        x.add(y);

    cout << "两个销售单的平均价格为:"<<x.avg_price() << endl;
    cout << y.avg_price() << endl;

    cout << endl << endl;
    cout << "Hello, class!" << endl;
    return 0;
}

相关文章

网友评论

      本文标题:C++之类-1

      本文链接:https://www.haomeiwen.com/subject/ovkjsqtx.html