大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←
问题:
解答:
main.cpp
#include <iostream>
#include "queuetp.h"
using namespace std;
int main()
{
QueueTp<Worker> lolas;
Worker w1;
lolas.queuecount();
w1.set();
lolas.enqueue(w1);
Worker w2;
lolas.dequeue(w2);
w2.show();
cout << "Bye.\n";
return 0;
return 0;
}
queuetp.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Worker
{
private:
string fullname;
long id;
public:
Worker():fullname("no one"),id(0L){}
Worker(const string &s,long n):fullname(s),id(n){}
~Worker() {};
void set();
void show()const;
};
template <class T>class QueueTp
{
private:
enum {Q_SIZE=10};
struct Node { T item; Node* next; };
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) :qsize(qs)
{
front = rear = NULL;
items = 0;
}
~QueueTp()
{
Node* temp;
while (front)
{
temp = front;
front = front->next;
delete temp;
}
}
bool isempty()const;
bool isfull()const;
int queuecount()const;
bool enqueue(const T& item);
bool dequeue(T& item);
};
template <class T>
bool QueueTp<T>::isempty()const
{
if (items == 0)return true;
else return false;
}
template <class T>
bool QueueTp<T>::isfull()const
{
return items == Q_SIZE;
}
template <class T>
int QueueTp<T>::queuecount()const
{
return items;
}
template <class T>
bool QueueTp<T>::enqueue(const T& item)
{
if (isfull())return false;
Node* temp = new Node;
temp->item = item;
temp->next = NULL;
items++;
if (front == NULL)
{
front = temp;
}
else
{
rear->next = temp;
}
rear = temp;
return true;
}
template <class T>
bool QueueTp<T>::dequeue(T& item)
{
if (isempty())return false;
item = front->item;
items--;
Node* temp = front;
front = front->next;
delete temp;
if (items == 0)
{
rear = NULL;
}
return true;
}
queuetp.cpp
#include "queuetp.h"
void Worker::set()
{
cout << "请输入工人的姓名:";
getline(cin, fullname);
cout << "请输入工人的id:";
cin >> id;
while (cin.get() != '\n')continue;
}
void Worker::show()const
{
cout << "工人姓名:" << fullname << endl;
cout << "工人id:" << id << endl;
}
运行结果:
考查点:
- 链队列
- 模板类
注意:
- 模板类成员函数的实现最好在一个文件中,不要分开,不然会报调不到函数的错误.
2024年9月10日21:48:36