C++-类

 私有和公有成员的定义和使用,构造函数的定义:

#include <iostream>

using namespace std;

class Sales_item
{
public:
	Sales_item(const std::string &book, unsigned units, double amount)	//这里的string要用const修饰
		: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) //不能定义为const	
	{
		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() const //只读,定义为const
	{
		return name;
	}
	std::string getAddress() 
	{
		return address;
	}
private:	//进行数据隐藏
	std::string name;
	std::string address;
};
int main()
{
	Person a("张飞", "花园街5号");
	cout << a.getName() << endl;
	cout << a.getAddress() << endl;

	Sales_item x((string("0-399-82477-1")), 2, 20.00);
	Sales_item y((string("0-399-82477-1")), 6, 48.00);

	if (x.same_isbn(y))
		x.add(y);

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

	return 0;
}

 类型别名,内联函数

#include <iostream>

using namespace std;

class Screen
{


public:

	typedef std::string::size_type index;
	//内联的成员函数
	Screen(index ht = 0, index wd = 0) :contents(ht * wd,'A'),cursor(0),height(ht),width(wd)
	{}
	//char get() const
	//{
	//	return contents[cursor];
	//}
	//char get(index r, index c) const
	//{
	//	index row = r * width;
	//	return contents[row + c];
	//}
	//函数声明
	Screen(index ht, index wd, const std::string& conts);
	char get() const;
	char get(index r, index c) const;
private:
	std::string contents;
	index cursor;
	index height, width;
};

Screen::Screen(index ht, index wd, const std::string& conts):contents(conts),cursor(0),height(ht),width(wd)
{}
char Screen::get() const	//加上inline还是内联的,
{
		return contents[cursor];
}
inline char Screen::get(index r, index c) const
{
	index row = r * width;
	return contents[row + c];
}
int main()
{
	Screen a(10,100);
	cout << a.get() << endl;
	cout << a.get(2, 8) << endl;

	Screen b(3, 6, "hello screen class");
	cout << b.get() << endl;
	cout << b.get(1, 2) << endl;

	Screen::index idx;	//类型别名可以在类的外部使用
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值