C++模板类嵌套类内部类局部类的区别

模板类就是将类定义成模板的形式。

C++中好像不区分内部类与嵌套类两个名词。

内部类与嵌套类都是指在类中定义类。

局部类是指在函数中定义类。

(c++不能在函数中定义函数(python可以)。c++在类中定义的函数也就是成员函数。)
(c++内部类与java内部类最大的区别就是:c++的内部类对象没有外部类对象的指针,不能访问外部类对象的非静态成员;java的非静态内部类对象有外部类对象的指针,能访问外部类对象的非静态成员。
java 中右多个内部类,还有匿名内部类。

 

通过嵌套类定义自己的队列Queue:

Queue类里面嵌套一个Node类:

编写Queue.h文件:

#ifndef QUEUE_H_
 
#define QUEUE_H_
 
template<class Type>
class Queue{
private:
    enum {Q_SIZE = 10};
    class Node{
    public:
        Type data;
        Node * next;
        Node(const Type data) : data(data), next(0) {}
    };  
    Node *front;
    Node *rear;
    int curSize;
    int maxSize;
public:
    Queue(int size = Q_SIZE);
    ~Queue();
    bool isFull() const;
    bool isEmpty() const ;
    bool enQueue(const Type data);
    bool deQueue();
    void tarverseQueue() const;
};
 
#endif

 编写Queue.cpp文件:

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <valarray>
#include "Queue.h"
using std::cout;
using std::endl;
 
template<class Type>
Queue<Type>::Queue(int size) : maxSize(size) {
    front = rear = 0;
    curSize = 0;
}
 
template<class Type>
Queue<Type>::~Queue() {
    Node *tmp;
    while (front != 0) {
        tmp = front;
        front = front->next;
        delete tmp;
    }
}
 
template<class Type>
bool Queue<Type>::isFull() const {
    return curSize >= maxSize;
}
 
template<class Type>
bool Queue<Type>::isEmpty() const {
    return curSize == 0;
}
 
template<class Type>
bool Queue<Type>::enQueue(const Type data) {
    if (isFull()) {
        return false;
    }   
    Node *node = new Node(data);
    if (front == 0) {
        front = node;
    } else {
        rear->next = node;
    }   
    rear = node;
    curSize++;
    return true;
}
 
template<class Type>
bool Queue<Type>::deQueue() {
    if (isEmpty()) {
        return false;
    }
    Node *tmpNode = front;
    front = front->next;
    delete tmpNode;
    if (front == 0) {
        rear = 0;
    }
    curSize--;
    return true;
}
 
template<class Type>
void Queue<Type>::tarverseQueue() const {
    Node *head = front;
    while (head != 0) {
        cout << head->data << endl;
        head = head->next;
    }
}
 
int main(int argc, char *argv[]) {
    Queue<int> queue(10);
    queue.enQueue(11);
    queue.enQueue(12);
    queue.tarverseQueue();
    return 0;
}

参考资料:

https://blog.csdn.net/solariens/article/details/52314896

https://blog.csdn.net/lw585625/article/details/84085249

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值