在另一个类中使用模板类

Using template class inside another class

本文关键字:另一个      更新时间:2023-10-16

我正在尝试创建一个将使用通用项目的队列。我收到一个错误与以下代码。

如何在另一个类中使用模板类?

以下是我到目前为止所做的尝试:

#include <iostream>
using namespace std;
template<class T>
class Item
{
public:
    Item(const T & item)
        : itemVal(item)
    {
    }
private:
    T itemVal;
};
class MyQueue
{
public:
    // Error #1
    void InsertNode(const Item & item); 
private:
    struct Node {
        // Error #2
        Item item; 
        struct Node * next;
    };
};
int main()
{
    Item<int> * element = new Item<int>(9);
    return 0;
}

Item不是类型,它是一个类模板。您需要提供模板参数。在本例中,int:

void InsertNode(const Item<int> & item)

struct Node{
    Item<int> item;
    Node<int> * next;
};

否则可以制作MyQueueNode类模板

最好重新设计你的类。

template<class T>
class MyQueue {
    struct Node {
        T item;
        Node * next;
    };
public:
    MyQueue();
    void InsertNode(const T & item);
private:
    Node * _root;
};

注:对不起,我的英语不好。

相关文章: