类的定义

#include <iostream>
#include <string>

using namespace std;

class Sales_item
{
public:
	Sales_item(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_item &rhs) const
	{
		return isbn == rhs.isbn;
	}

	void add(const Sales_item &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)  // 这是构造函数初始化列表,
           {
		   /*name = nm;
		   address = addr;*/
              }
   std::string getName()   // public 是共有的成员可以在类的外部被调用,public是函数成员
           {
		   return name;
             }
   std::string getAddress()
           {
		   return address;
            }
private: 
	std::string name; // private 是私有的成员只能在内部使用,
    std::string address;
};

int main()
{
	Person a("小崔","中州路与九都路交叉口"); // 调用类的时候只能调用类的公有成员,private是数据成员
	cout << a.getName() << ", " << a.getAddress();
	cout << endl;
	a.getAddress();
	a.getName();

	Sales_item x(string("0-399-254-12"), 2, 20);
	Sales_item y(string("0-399-254-12"), 5, 40);
	if (x.same_isbn(y))
		x.add(y);

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

	return 0;
}

你可能感兴趣的:(类的定义)