2011-04-08 66 views
1

好吧,现在已经在C++上工作了大约2天。刚刚完成JavaScript ...引用在模板类中声明的结构

我正在使用链接列表模板队列。当我尝试从withink queue.cpp

//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 `;' 

任何帮助PLZ?提前致谢。

回答

3

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

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

Node * ptr = original.front->next; 

你有内环路什么也都可以工作,其中明确指定模板参数。但是,请注意,由于Node是私有的,除非您将模板实例化为friend,您必须为当前实例指定模板参数,因此Queue<Object>::Node没问题,但Queue<int>::Node不是,除了Queue<int>本身。

+0

是的!谢谢威廉斯先生! – Bobby 2011-04-08 07:24:43

0

一旦复制构造函数启动,<Object>将随时需要时与Queue一起隐式添加。对于所有平台的兼容性,应申报喜欢以下内容:

front = back = new typename Queue::Node; //this is line 26 
0

这里有一个稍微不同的建议:

// Node is defined within same "class { }", so it needs no "::" qualification 
front = back = new Node; 

在任何情况下,你的代码给出编译罚款(http://ideone.com/UrLN0),所以我不知道是否有这里有什么别的东西。

没有模板参数的标识Queue指的是模板本身内部的当前实例。

+0

在C++ 0x中,他需要'Queue :: Node'之前的'typename'。您尝试的编译器可能会实现C++ 0x的含义,这意味着您可以将其关闭。 – 2011-04-09 11:56:15

+0

@Johannes:如果没有使用'::',则不需要'typename',对吧? – Potatoswatter 2011-04-10 01:04:37

1

你的编译器使用了什么?你的代码不应该有任何问题。因为在班级内使用名称Queue时,相当于Queue<Object>

这是一个在C++标准,

像正常(非模板)类, 类模板有一个 注入的类名(第9条)。 注入类名可以与 一起使用,也可以不使用模板参数列表。 如果在没有 模板参数列表的情况下使用它,则它是 等效于注入类名称 后跟模板参数 包含在<>中的类模板。 当它与一个 模板参数列表使用的,它指的是 指定类模板 特殊化,这可能是 当前专业化或另一个 专业化。