c++類的嵌套模闆
1.作用域
如果一個嵌套類在另一個類的私有部分聲明的,嵌套類對于這個類是可見的,對于外界是不可見的。
如果一個嵌套類在另一個類的公有部分聲明的,則允許在這個類和外界使用這個嵌套類。
2.通路權限
嵌套類的私有部分不允許在聲明嵌套類中的這個類通路
queuetp.h類的初始
#ifndef _QUEUETP_H_
#define _QUEUETP_H_
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
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;
const int qsize;
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;
}
}
//添加一個Node
template <class Item>
bool QueueTP<Item>::enqueue(const Item & item)
{
if( isfull() )
return false;
Node * add = new Node(item);
items++;
if( front == 0)
{
front = add;
cout << "第一個成員是:"<< front->item <<endl;
}
else
rear->next = add;
rear = add;
return true;
}
//将前面item放入item的變量中并從queue中移除
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
nested.cpp調用
#include<string>
#include "queuetp.h"
int main()
{
QueueTP<string> cs(5);
string temp;
while( !cs.isfull())
{
cout << "請輸入你的名字\n";
cout << "name: ";
getline(cin,temp);
cs.enqueue(temp);
}
cout << "隊列滿\n";
while (!cs.isempty())
{
cs.dequeue(temp);
cout << "隊列移除" << temp << "...\n";
}
return 0;
}
makefile
CC = g++
objects = nested.o
program:$(objects)
$(CC) -o program $(objects)
clean:
rm -rf *.o program
運作結果:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL90TQiNnRtlFM5IjYtZkMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLyMzM4QTMwcTMyIjMxAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)