我是靠谱客的博主 耍酷自行车,最近开发中收集的这篇文章主要介绍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;
}


最后

以上就是耍酷自行车为你收集整理的C++程序设计语言练习10.12 C++的普通类表示的全部内容,希望文章能够帮你解决C++程序设计语言练习10.12 C++的普通类表示所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部