C++程序设计语言练习10.12 C++的普通类表示

答案的代码如下:


#include <iostream>
#include <typeinfo>

#include <stdexcept>
#include <string>

struct Char_queue{
	inline Char_queue(unsigned capacity = default_capacity);
	~Char_queue(){ delete[] queue_; }
	bool empty()const { return head_ == tail_; }
	inline char dequeue();
	inline void enqueue(char);
	bool full() const { return head_ == (tail_ + 1) % capacity_; }
	static bool const fixed_capacity = true;
private:
	static unsigned const default_capacity = 32;
	char* queue_;
	unsigned head_, tail_;
	unsigned const capacity_;
};


inline Char_queue::Char_queue(unsigned n)
:queue_(new char[n + 1]),head_(0), tail_(0), capacity_(n + 1){}

inline char Char_queue::dequeue(){
	if (!empty())
	{
		char c = queue_[head_];
		head_ = (head_ + 1) % capacity_;
		return c;
	}
	else{
		throw std::underflow_error(std::string("queue"));
	}
}

inline void Char_queue::enqueue(char c)
{
	if (!full())
	{
		queue_[tail_] = c;
		tail_ = (tail_ + 1) % capacity_;
	}
	else
	{
		throw std::overflow_error(std::string("queue"));
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	Char_queue q(4);
	while (1)
	{
		if (q.empty()){ std::cout << "Queue is empty.\n"; }
		else if (q.full()){ std::cout << "Queue is full.\n"; }
		char cmd, ch;
		std::cin >> cmd;
		try{
			switch (cmd){
			case 'e':case 'E':
				std::cin >> ch;
				q.enqueue(ch);
				break;
			case 'd': case 'D':
				std::cout << "Dequeued" << q.dequeue() << '\n';
				break;
			case 'q': case 'Q':
				std::cout << "Quitting!\n";
				return 0;
			default:
				std::cerr << "Invalid command!\n";
			}
		}
		catch (std::exception &x){
			std::cerr << "Caught exception " << typeid(x).name() << " (" << x.what() << ")\n";
		}

	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值