编程语言
首页 > 编程语言> > c++学习-oop-类定义1

c++学习-oop-类定义1

作者:互联网

/*
	Date: 08/03/21 13:38
	Description: 类定义1
	类成员
	构造函数
	成员函数
	访问标号实施抽象和封装
		public
		private
		protected 
*/

#include<iostream>

using namespace std;

//  	销售	项目
class Sales_item
{
public:
	Sales_item(string book,unsigned  units,double amout):isbn(book),units_sold(units),revenue(amout)
	{
		
	}
	
	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:
	string isbn;		//书号 
	unsigned  units_sold;//销售数量 
	double revenue;		//总金额 
};


class Person
{
	//成员 
public:
	Person(){}
	Person(const string& nm,const string& addr):name(nm),address(addr) 	//初始化列表 
	{
//		this->name = nm;
//		this->address = add;
	}
	string getName() const  //这个函数不会修改数据,只会把数据读出来 
	{
		return name;	
	} 
	string getAddress() const 
	{
		return address;
	}

private:		//默认为私有 
	string name;
	string address;

};

int main()
{
	Person a("bill","usa");
	//	a.name;	[Error] 'std::string Person::name' is private

	cout<<a.getName()<<","<<a.getAddress()<<endl;
	
	cout<<"测试一下"<<endl;
	
	Sales_item x("0-399-82477-1",2,20.00);
	//	[Error] no matching function for call to 'Sales_item::Sales_item(std::string, int, double)'
	//[Note] no known conversion for argument 1 from 'const char*' to 'std::string& {aka std::basic_string<char>&}'
	Sales_item y("0-399-82477-1",6,48.00);
	
	if(x.same_isbn(y))
	{
		x.add(y);
	}
	cout<<"两个销售单的平均价是:"<<x.avg_price()<<endl;
	
	return 0;
}

标签:const,string,sold,c++,name,oop,units,isbn,定义
来源: https://blog.csdn.net/flamesfather/article/details/114534621