C++_嵌套类
2015-08-10 21:28
393 查看
在C/C++中,可以将结构体/类的声明放在另一个类中。在另一个类中声明的类被称为嵌套类,它通过新的类型类作用域来避免名称混乱。
嵌套类的作用域:
1。如果嵌套类是在另一个类的私有部分声明的,则只有后者知道它。
2。如果嵌套类是在另一个类的保护部分声明的,则它对于后者来说是不可见得。
3。如果嵌套类在另一个类的共有部分声明的,则允许后者,后者的派生类以及外部世界使用它,因为它是共有的。
示例嵌套类与模板组合使用:
将Queue类的定义转换为模板时,不会对嵌套类带来问题。
Queue.h头文件
测试文件
main.cpp
测试截图
嵌套类的作用域:
1。如果嵌套类是在另一个类的私有部分声明的,则只有后者知道它。
2。如果嵌套类是在另一个类的保护部分声明的,则它对于后者来说是不可见得。
3。如果嵌套类在另一个类的共有部分声明的,则允许后者,后者的派生类以及外部世界使用它,因为它是共有的。
示例嵌套类与模板组合使用:
将Queue类的定义转换为模板时,不会对嵌套类带来问题。
Queue.h头文件
#ifndef QUEUETP_H_ #define QUEUETP_H_ template <class Item> class QueueTP { private: enum{ Q_SIZE = 10}; class Node { public: Item item; Node * next; Node(const Item &i) :item(i), next(0){} }; Node * front; Node * rear; int items; //current number of items in Queue const int qsize; //maximum number of items in Queue QueueTP(const QueueTP &q) :qsize(0){} QueueTP & operator=(const QueueTP &q){ return *this; } public: QueueTP(int qs = Q_SIZE); ~QueueTP(); bool isempty()const{ return items == 0; } bool isfull()const{ return items == qsize; } int queuecount()const{ return items; } bool enqueue(const Item &item); bool dequeue(Item &item); }; template<class Item> QueueTP<Item>::QueueTP(int qs) :qsize(qs){ front = rear = 0; items = 0; } template<class Item> QueueTP<Item>::~QueueTP(){ Node * temp; while (front != 0){ temp = front; front = front->next; delete temp; } } template<class Item> bool QueueTP<Item>::enqueue(const Item &item){ if (isfull()) return false; Node *add = new Node(item); if (add == NULL){ return false; } items++; if (front == 0) front = add; else rear->next = add; rear = add; return true; } template<class Item> bool QueueTP<Item>::dequeue(Item &item){ if (front == 0) return false; item = front->item; items--; Node * temp = front; front = front->next; delete temp; if (items == 0) rear = 0; return true; } #endif
测试文件
main.cpp
#include <iostream> #include <string> #include "Queue.h" int main(){ using std::cin; using std::cout; using std::string; using std::endl; QueueTP<string> cs(5); string temp; while (!cs.isfull()) { cout << "Please enter your name. You will be " << "served in the order of arrival.\n" "name :"; getline(cin, temp); cs.enqueue(temp); } cout << "The queue is full. Processing begins!\n"; while (!cs.isempty()) { cs.dequeue(temp); cout << "Now processing " << temp << "...\n"; } return 0; }
测试截图
相关文章推荐
- c++学习笔记
- 线性表的顺序存储结构
- C语言 - 排序总结
- c++ 使用算法时确保目标区间足够大
- C++/CLI
- C语言 - 经典程序设计100例
- C语言-07-预处理、typedef、static和extern
- C++使用简单的函数指针
- 一起talk C栗子吧(第三十四回:C语言实例--巧用溢出计算最值)
- C/C++ static使用方法注意
- JSON for C++ 介绍1
- C语言-FunctionPointer
- c与c++中struct区别
- C语言-DynamicMemory
- C++标准程序库笔记(2)
- [c语言]冒泡排序-------对折判断法
- [c语言]冒泡排序升级版------选择排序简单版
- C语言-Pointer(high)AndMacro
- C语言 sscanf,sprintf函数 使用总结
- C语言-Pointer