AURA622 2021-04-13 16:51 采纳率: 50%
浏览 38
已采纳

求助!使用c++模板实现自定义队列报错

#include<iostream>
using namespace std;
#include<string>
class Person
{
public:
	
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}

	string m_Name;
	int m_Age;
};
template<class T>
class Queue
{
public:
	Queue()
	{
		
		this->head = new Node<T>(NULL,NULL);
		this->last = NULL;
		this->N = 0;
	}
	bool isEmpty(){return N == 0;}
	int size(){return N;}
	T pop()
	{
		if (this->size()==0)
		{
			return NULL;
		}
		Node<T>* oldfirst = head->next;
		head->next = oldfirst->next;
		N--;
		if (this->isEmpty())
		{
			last = NULL;
		}
		return oldfirst->item;
	}
	void push(T t)
	{
		if (this->size() == 0)
		{
			this->head->next = new Node<T>(t, NULL);
		}
		else
		{
			
			Node<T>* newfirst = new Node<T>(t, head->next);
			head->next = newfirst;
			
		}
		N++;
	}


	
	template<class T>
	class Node
	{
		
	public:
		Node(T i,Node* n)
		{
			this->item = i;
			this->next = n;
		}
	
		T item;
		Node<T>* next;
	};
	int N;
	Node<T>* head;
	Node<T>* last;
};
void main()
{
	Person p1("唐僧", 30);
	Person p2("孙悟空", 1000);
	Person p3("猪八戒", 900);
	Person p4("沙僧", 800);
	Queue<Person> q;
	q.push(p1);
	q.push(p2);
	q.push(p3);
	q.push(p4);
	while (q.size() != 0)
	{
		cout << q.pop().m_Name << "  " << q.pop().m_Age << endl;
	}
	/*Queue<char> q;
	q.push('1');
	q.push('d');
	q.push('3');
	q.push('f');
	q.push('3');
	while (q.size() != 0)
	{
		cout << q.pop()   << endl;
	}*/
	cout << endl;
	system("pause");
	return;
}

使用自定义的类放入队列时出错,错误列表: return无法从“int” 转为“Person”,请问如何解决?第24行this->head = new Node<T>(NULL,NULL); 也出现同样错误 :参数1无法从“int” 转为“Person”,可是明明参数1 是模板T啊?实在是搞不懂

  • 写回答

4条回答 默认 最新

  • lemon-l 2021-04-13 17:00
    关注

    Node的构造函数第一个参数为Person,你传NULL进去肯定不行啊。改为new Node<T>(Person("",0),NULL);试试

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题