我使用模板制作了一个基于数组的队列,以便用户可以决定队列中保存什么类型的数据,但我无法弄清楚如何收集输入,然后从中创建该数据类型的队列。
这是我的队列
#include <memory>
using namespace std;
template<class itemType>
class Queue
{
private:
unique_ptr<itemType []> queueArray;
int queueSize;
int front;
int rear;
int numItems;
public:
Queue(int);
itemType peekFront();
void enqueue(itemType item);
void dequeue();
bool isEmpty() const;
bool isFull() const;
void clear();
};
我已经尝试过这种方法和许多其他方法,但无法弄清楚如何判断用户输入的数据类型,然后使用该类型的数据创建一个队列。
int main()
{
const int MAXSIZE = 5;
int choice;
cout << "1. integer queue\n" << "2. string queue\n" << "3. float queue\n";
choice = menu();
if(choice == 1)
{
Queue<int> newQueue(MAXSIZE);
int data;
}
else if(choice == 2)
{
Queue<string> newQueue(MAXSIZE);
string data;
}
else if(choice == 3)
{
Queue<float> newQueue(MAXSIZE);
float data;
}
else
cout << "Number needs to be 1-3." << endl;
cout << "Enter an item to add" << endl;
cin >> data;
newQueue->enqueue(data);
感谢大家的帮助!我几乎已经完成了,但是现在我已经拥有了所有虚拟函数,如何调用 peekFront() ?既然虚函数不能返回 itemType,对吗?
最佳答案
你需要运行时多态性来解决这个问题。这可以通过基类来实现:
class IQueue {
virtual ~IQueue() = default;
virtual void enqueue(istream&) = 0;
};
template<class itemType>
class Queue : public IQueue
{
//...
public:
void enqueue(istream& is) override {
itemType item;
is >> item;
enqueue(item);
}
//...
};
并用作指针
int main() {
//...
unique_ptr<IQueue> newQueue;
//...
if(choice == 1)
{
newQueue.reset(new Queue<int>(MAXSIZE));
int data;
}
//...
newQueue->enqueue(cin);
//...
}
或者像std::variant
之类的东西。
关于c++ - 如何根据用户输入创建模板对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58928944/