gpt4 book ai didi

c++ - 引用在模板类中声明的结构

转载 作者:行者123 更新时间:2023-11-30 02:09:18 25 4
gpt4 key购买 nike

好的,现在已经使用 C++ 大约 2 天了。之前刚做过javascript...

我正在使用链表制作模板队列。当我尝试从 withink queue.cpp 中创建一个新的 Node 结构时,我的编译器不喜欢它

//queue.h:
template <class Object>
class Queue
{
public:
Queue(); // Default
Queue(const Queue& original); // Copy

~Queue(); // Destructor

const Queue& operator=(const Queue& rightHandSide); //overloaded op

bool isEmpty() const;

bool enqueue(const Object& d);
bool dequeue(Object& d);

private:
// Node definition
struct Node
{
Object data;
Node * next;
};
// Queue data members
Node * front, * back;
};

因此,在我的复制构造函数中,我需要创建一个新节点。

//queue.cpp
template <class Object>
Queue<Object>::Queue(const Queue& original)
{
if (original.isEmpty()) {
front = back = NULL;
} else {
front = back = new Queue::Node; //this is line 26
front->data = original.front->data;
Queue::Node * ptr = original.front->next;
while (ptr != NULL) {
back->next = new Queue<Object>::Node;
back = back->next;
back->data = ptr->data;
ptr = ptr->next;
}
}
}

queue.cpp: In copy constructor âQueue<Object>::Queue(const Queue<Object>&)â:
queue.cpp:26: error: expected type-specifier
queue.cpp:26: error: expected `;'

有什么帮助吗?提前致谢。

最佳答案

Queue 的内部成员函数,可以直接引用Node .

front = back = new Node;                 //this is line 26

Node * ptr = original.front->next;

您在循环内的内容也可以工作,您可以在其中明确指定模板参数。但是,请注意自 Node是私有(private)的,除非您进行模板实例化 friend s彼此,必须指定当前实例化的模板参数,所以Queue<Object>::Node很好,但是 Queue<int>::Node不是,除了for Queue<int>本身。

关于c++ - 引用在模板类中声明的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5591546/

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