C++语言的确是一个强大的编程语言,与C语言有很大的差异,虽说许多基本思想是一样的,比如结构体和类,其实如果你有C语言的基础,学习这个class类还是比较容易上手的,在struct结构体的基础上增加私有和保护的元素,这样可以使得class类中的数据访问更加安全,而模板的产生则是体现了一种重载的机制,可以通过一个类实现许多不同类型的数据的调用问题。从而极大的简化了开发过程,使得使用起来更加方便。
具体example如下
template<class T>
class Queue
{
private:
struct Node
{
T val;
Node* next;
Node(T x):val(x),next(NULL){};
};
private:
Node* head;
int thesize;
public:
Queue()
{
head = NULL;
thesize = 0;
}
~Queue()
{}
void push(T val)
{
Node* temp = head;
Node* node = new Node(val);
if(thesize == 0)
{
node->next = temp;
head = node;
thesize++;
return;
}
while(temp->next!= NULL)
{
temp = temp->next;
}
if(temp->next == NULL)
{
node->next = temp->next;
temp->next = node;
thesize++;
return;
}
}
void Print() const
{
Node* temp = head;
if(temp == NULL)
cout<<"Error:Print failed!"<<endl;
while(temp != NULL)
{
cout<<temp->val<<endl;
temp = temp->next;
}
}
int cap() const{
return thesize;
}
};
这是一个简单的队列的模板类,template加在类的前面,将类中的统一数据类型用T来泛指,这样就可以实现任意类型加入到队列中去,十分方便!