gpt4 book ai didi

C++ |无法推断 T | 的模板参数没有参数的空函数 (display() )

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:39:12 25 4
gpt4 key购买 nike

我正在使用 C++ 模板创建一个动态队列以供进一步练习。大多数重要的函数似乎工作得很好,除了我定义的最后两个 - 没有参数的空函数。

#include <iostream>
#include <string>
using namespace std;


template <typename T>
class DynamicQueue
{
private:
// Structure for the queue nodes
struct QueueNode
{
T value; // Value in a node
QueueNode *next; // Pointer to the next node
};
QueueNode *top; // The top of the queue
QueueNode *bottom; // The bottom of the queue
int numItems; // Number of items in the queue
public:
DynamicQueue() {
top = nullptr;
bottom = nullptr;
numItems = 0;
}
~DynamicQueue() {
delete[] top;
delete[] bottom;
}
template <typename T>
bool isEmpty() const {
bool empty;
if (numItems > 0)
empty = false;
else
empty = true;
}
template <typename T>
void display() const {
QueueNode* temp = top;
while (temp != nullptr) {
cout << temp->value << endl;
temp=temp->next;
}
}
template <typename T>
void clear() {
T temp;
while (!isEmpty()) {
dequeue(data);
}
}
};

有一个 enque 和一个 deque 函数,我没有包含在代码中,因为它们工作得很好。主要功能看起来有点像:

int main() {

string str;
int number;

DynamicQueue<string> strQ;
DynamicQueue<int> intQ;

strQ.enqueue("Word number 1");
strQ.enqueue("2");

strQ.dequeue("2");
strQ.display();

intQ.enqueue(1);
intQ.enqueue(2);
int placehold;
intQ.dequeue(placehold);
intQ.display();

strQ.clear();
intQ.clear();

getchar();
return 0;
}

编译器产生以下错误:

错误 C2672:“DynamicQueue::display”:找不到匹配的重载函数

错误 C2783:“void DynamicQueue::display(void) const”:无法推断“T”的模板参数

注意:参见“DynamicQueue::display”的声明

我知道问题出在我做错了模板。但我似乎不明白正确的做法。

(clear()函数也有同样的问题)

最佳答案

您似乎遇到了模板阴影问题,因为您在类方法定义上重新声明了模板 T,这在您的情况下是多余的。

如果您在类定义之外实现您的方法,那将是必要的。

内部类定义:

void clear() {
// Stuff
}

外面:

template <typename T>
void DynamicQueue<T>::clear() {
// Stuff
}

您最初使用的语法是特定于方法的新模板声明,例如入队它可能是:

template<typename... Args>
void enqueue(Args&&... args)
{
// Create new node
QueueNode* new_node = new QueueNode();
bottom->next = new_node;

new (&(new_node->value)) T(args...);
bottom = new_node;
}

和外部声明:

template<typename T>
template<typename... Args>
void DynamicQueue<T>::enqueue(Args&&... args)
{
// Create new node
QueueNode* new_node = new QueueNode();
bottom->next = new_node;

new (&(new_node->value)) T(args...);
bottom = new_node;
}

但是模板参数的名称不能是 T 否则你会遇到阴影问题

关于C++ |无法推断 T | 的模板参数没有参数的空函数 (display() ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55253805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com