为了账号安全,请及时绑定邮箱和手机立即绑定

用模板实现的问题

使用类模板的话,遍历的输出应该怎么写,因为输出int和类的方法不一样 请大神告知

正在回答

4 回答

不好意思,第85行的QueueEmpty()函数调用多了一对括号。

0 回复 有任何疑惑可以回复我~
void MyQueue::QueueTraverse(){
    for(int i=m_iHead; i < m_iHead + m_iQueueLen; i++){
        m_pQueue[m_iHead].printInfo();
    }
}


//其中printInfo()是自定义类型实现的函数,例如
void Customer::printInfo(){
    cout << ”姓名: " << m_strName << endl;
    cout << "年龄: " << m_iAge << endl;
    cout << endl;
}

再贴上一个我实现的吧,直接复制下面的代码可运行。

#include <iostream>
#include <string>

using namespace std;


class Customer{
public:
	Customer(){
		//需要默认构造函数
	}
	
	Customer(string name, int age){
		m_strName = name;
		m_iAge = age;
	}

	void printInfo() const{
		cout << "姓名: " << m_strName << endl;
		cout << "年龄: " << m_iAge << endl;
		cout << endl;
	}
	
private:
	string m_strName;
	int m_iAge;
};




template <class T>
class MyQueue{
public:
	MyQueue(int queueCapacity){
		m_iQueueCapacity = queueCapacity;
		m_iQueueLen = 0;
		m_iHead = 0;
		m_iTail = 0;
		m_pQueue = new T[queueCapacity];
	}
	
	~MyQueue(){
		delete[] m_pQueue;
	}
	
	void QueueClear(){
		m_iQueueLen = 0;
		m_iHead = 0;
		m_iTail = 0;
	}
	
	bool QueueEmpty() const{
		if(m_iQueueLen==0){
			return true;
		}
		else{
			return false;
		}
	}
	
	bool QueueFull() const{
		if(m_iQueueLen==m_iQueueCapacity){
			return true;
		}
		else{
			return false;
		}
	}
	
	bool EnQueue(T element){
		if(QueueFull()){
			return false;
		}
		else{
			m_pQueue[m_iTail] = element;
			m_iTail ++;
			m_iTail = m_iTail % m_iQueueCapacity;
			m_iQueueLen ++;
			return true;
		}
	}
	
	bool DeQueue(T &element){
		if(QueueEmpty()()){
			return false;
		}
		else{
			element = m_pQueue[m_iHead];
			m_iHead ++;
			m_iHead = m_iHead % m_iQueueCapacity;
			m_iQueueLen --;
			return true;
		}
	}
	
	void QueueTraverse(){
		for(int i = m_iHead; i < m_iHead + m_iQueueLen; i++){
			m_pQueue[i%m_iQueueCapacity].printInfo();
		}
	}
	
private:
	T* m_pQueue;
	int m_iHead;
	int m_iTail;
	int m_iQueueLen;
	int m_iQueueCapacity;
};





int main(int argc, char *argv[]) {
	MyQueue<Customer>* p = new MyQueue<Customer>(4);
	p->EnQueue(Customer("imooc", 20));
	p->QueueTraverse();
}


0 回复 有任何疑惑可以回复我~

template <class T>

void MyQueue::QueueTraverse()

{

// 里面T即你需要的类型

}


0 回复 有任何疑惑可以回复我~

template <class T>

void MyQueue::QueueTraverse(){

 //some code

}

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

用模板实现的问题

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信