【问题标题】:How do i call a template class in the main function如何在主函数中调用模板类
【发布时间】:2020-10-18 20:03:33
【问题描述】:

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

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


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


调用函数 moveNthFront 后: 队列 ={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>;

}

【问题讨论】:

  • 如果您在代码中搜索“list”并将所有不代表 std::list 的内容替换为不同的单词会怎样?

标签: c++ list templates


【解决方案1】:

您收到错误消息,因为

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&lt;int&gt;; 实际上是一个Queue,以int 作为模板参数!但就像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};
}

【讨论】:

    猜你喜欢
    • 2017-05-04
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2012-10-24
    相关资源
    最近更新 更多