c++ - 好友类声明错误

标签 c++

<分区>

我正在实现一个单向链表。这是节点类

template <typename T> class node{

    friend class slist<T>;
    public:
        explicit node():data(0), next(NULL){}

    private:
        T data;
        node<T> *next;

};

这是列表类。

template<typename T> class slist{
    public:
        slist():head(NULL){}


        bool empty(){
            return head == NULL;
        }

        void add_front(const T& data){
            if(head == NULL){
                node<T>* n = new node<T>();
                n->data = data;
                n->next = NULL;
                head = n;
                return;
            }
            node<T>* n = new node<T>();
            n->data = data;
            n->next = head;
            head = n;
        }

        void remove_front(){
            if(head == NULL) return;
            node<T>* old = head;
            head = old->next;
            delete old;
        }

        void print_list(){
            if(head == NULL) return;
            while(!empty()){
                std::cout<<head->data<<std::endl;
                head = head->next;
            }
        }

        ~slist(){

            while(!empty()) remove_front();

        }

    private:
        node<T>* head;
};

如果我将节点中的成员声明为公共(public)的,则实现工作得很好。然而,当我将它们声明为私有(private)并将 slist 设为友元类时,我收到以下错误。

In file included from src.cpp:3:
./slist.hpp:5:28: error: redefinition of 'slist' as different kind of symbol
template<typename T> class slist{
                           ^
./node.hpp:4:15: note: previous definition is here
        friend class slist;

我显然可以找到单链表的其他实现,但我试图了解这里出了什么问题。因此,请不要将未经请求的建议称为“google it”。谢谢。

最佳答案

需要将List类转发声明为模板类:

#include <iostream>

template<typename T> class List; //<< fwd decl

template<typename T> class Node {
    int i;
public:
    friend class List<T>; //<< usage same as you have now
    Node() : i(123) {}
    int value() { return i; }
};

template<typename T> class List { //<< definition
public:
    List(Node<T>* node) { node->i++; }
};

int main() {
    Node<int> node{};
    List<int> list{&node};
    std::cout << node.value() << "\n";
}

http://ideone.com/2RUWgj

关于c++ - 好友类声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038519/

相关文章:

c++ - Caffe 中的批处理模式 - 没有性能提升

c++ - 获取 SDL_Texture 中单个像素的 SDL_Color

c++ - 对 std::unordered_set 中元素的指针/引用

C++ std::list with struct containing list with struct

c++ - 如何包含 mysql header ?

c++ - C++中多重继承对象的内存布局

c++ - C++ 中 Char 数组的比较和排序

c++ - 将多个非原始递归调用转换为迭代解决方案

c++ - 使用模板重载运算符,但防止重新定义

c++ - '字节' : ambiguous symbol error when using of Crypto++ and Windows SDK