C++(OOP):定义基类和派生类

#include <iostream>

using namespace std;

// 基类
class Animal
{
	// 成员略
};

// 继承 or 派生
class Dog: public Animal
{
	// 成员略
};

// 继承 or 派生
class Cat: public Animal
{
	// 成员略
};

int main()
{
	Animal A;
	Dog B;
	Cat C;
			
	return 0;
}
#include <iostream>
#include <string>

using namespace std;

class Item_base
{
public: // 公有
	Item_base(const std::string &book = "",
			double sales_price = 0.0):
			isbn(book),price(sales_price){}

	std::string book() const
	{
		return isbn;
	}

	// 虚函数  在子类可以重新定义
	virtual double net_price(size_t n) const
	{
		return n * price;
	}
private: // 私有
	std::string isbn;
protected: // 受保护
	double price;
};

class Bulk_item: public Item_base
{
public:
	Bulk_item(const std::string &book="",
			double sales_price = 0.0,
			size_t qty =0,
			double disc_rate = 0.0):
		Item_base(book, sales_price), min_qty(qty),
		discount(disc_rate){}
	
	void test()
	{
		// 受保护的只能继承
		cout << price << endl;
		// 私有的并没有继承
		//cout << isbn << endl;
		}

	void test2(const Bulk_item &d, const Item_base &b)
	{
		cout << d.price << endl;	
		// 受保护的能被它所在的类使用,友元使用,或者被继承
		//cout << b.price << endl;
	}

	double net_price(size_t cnt) const
	{
		if(cnt >= min_qty)
			return cnt * (1 - discount) * price;
		else
			return cnt * price;
	}

private:
	size_t min_qty;
	double discount;
};

int main()
{
	Item_base item("0-12-3456-789", 9.9);
//	cout << item.x << endl;
//	cout << item.isbn << endl;
//	cout << item.price << endl;

	Bulk_item item2("0-12-3456-789", 9.9, 10, .12);
//	cout << item2.x << endl;
	item2.test();
	item2.test2(item2, item);
//	cout << item2.price << endl;
//	cout << item2.isbn << endl;
//	cout << item2.min_qty << endl;
//	cout << item2.discount << endl;
		
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值