-1

I am learning data structure using C++. I copy the code into my computer just like the book tells me, but the compiler shows Chain is not a class template.

template <class T>
class ChainNode{
    friend class Chain<T>;

private:
    T data;
    ChainNode<T> *link;
};

template <class T>
class Chain{
public:
    Chain(){ first = 0; }
    ~Chain();
    bool isEmpty() const { return first == 0;}
    int Length() const;
    bool Find(int k, T &x) const;
    int Search(const T &x) const;
    Chain<T>& Delete(int k, T &x);
    Chain<T>& Insert(int k, const T &x);
    void Output(ostream &out) const;

private:
    ChainNode<T> *first;   //指向第一个节点的指针
};

There is the error reported by the compiler: template class error

How to fix the problem?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
孙维松
  • 47
  • 4

1 Answers1

3

You need to forward declare Chain before the friend declaration, to tell the compiler that it's a template. i.e.

// forward declaration
template <class T>
class Chain;

template <class T>
class ChainNode {

    // friend declaration
    friend class Chain<T>;
    ...
};

// definition    
template <class T>
class Chain {
    ...
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405