首页 > 解决方案 > 如何在主函数中调用模板类

问题描述

这是我作为任务给出的问题,但是我收到错误''std::list':使用类模板需要模板参数列表'。目前我只是想让程序在运行时显示列表。

编写函数 moveNthFront 的定义,该函数将正整数 n 作为参数。该函数将队列的第 n 个元素移到前面。其余元素的顺序保持不变。例如,假设:


队列 = {5, 11, 34, 67, 43, 55} 和 n=3


调用函数 moveNthFront 后:Queue ={34, 5, 11, 67, 43, 55}。


(i)为静态队列模板类实现上述功能。


(ii)为一个动态队列模板类实现上述功能


这是我的类头代码:

#include <iostream>
#include <list>

using namespace std;

template <class T>
class Queue {

    T QueueList;
    T position;

public:
    // Constructs the queue class and defined the queue list and value for n
    Queue(T list, T n) {
        QueueList = list;
        position = n;

        list = { 5, 11,34,67,43, 55 };
        n = 0;
    };

    T PrintQueue();
    T MoveNthFront();
};

template <class T>
T Queue<T>::PrintQueue() {
    cout << list;
    return;
}

template <class T>
T Queue<T>::MoveNthFront() {

}

这是我的主要功能代码(我知道它不起作用,我只是不知道我需要做什么才能使它起作用,它不完整)

#include <iostream>
#include "Queue.h"

int main() {

    int n;
    int Queuelist;

    Queue<int>;

}

标签: c++listtemplates

解决方案


您收到错误消息,因为

template <class T>
T Queue<T>::PrintQueue() {
    cout << list;
    return;
}

被解释为

template <class T>
T Queue<T>::PrintQueue() {
    cout << std::list;
    return;
}

因为您使用using namespace std;(并且没有名为列表的变量)。但是std::list需要一个模板参数,因此会出错。

所以有两件事,不要使用using namespace std;并且总是完全作用域:(std::cout而不是cout),并且您“列出”不是您班级的成员,您可能打算将另一个成员传递给std::cout.

至于模板,您实际上(几乎)正确调用了它。Queue<int>;实际上是一个Queuewith intas 模板参数!但就像 一样int,您需要为初始化分配一个变量:

int main() {
    int n;
    int Queuelist;

    Queue<int> myQueue;
}

但这会调用 您尚未定义的 myQueue的默认构造函数。您可能打算致电Queue(T list, T n)

int main() {
    int n;
    int Queuelist;

    Queue<int> myQueue{n,Queuelist};
}

推荐阅读