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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分