简体   繁体   中英

C++ declaring multiple classes in one header

I got an assignment where I am supposed to create a Linked list by using CRTP. I got some starting code/suggestion on how to define the classes in their respective header files. I have omitted some code below:

Link.h

#include <iosfwd>

template<class T>
class List;

template<class T>
class Link {
    Link* next;

    friend class List<T>;

public:
    Link();

    virtual ~Link() = default;
  //etc...

List.h

#include "Link.h"


template<class T>
class List : public Link<T> {
public:
    List();

    T* First();

    T* Last();
    //Etc...

This code compiles without any errors. Now my question is about the two first lines in Link.h, template<class T> class List; . I experimented a little bit and realized that Link.h won't compile without that class definition beacuse of the friend class List<T> statement. But why can't I just write #include "List.h" and remove the inheritance inside List.h and just use that definition from the start? I have tried this of course and get the error

"error: 'List' is not a class template
     friend class List<T>;"

it would look like this:

Link.h

#include <iosfwd>
#include "List.h"


template<class T>
class Link {
    Link* next;

    friend class List<T>;

public:
    Link();

    virtual ~Link() = default;

List.h

#include "Link.h"


template<class T>
class List {
public:
    List();

    T* First();

Try to use a unique template in one file only or in files that build upon each other sequentially, not equally. In your case, you should probably move all of your files to one. Your .h files seem to mirror each other, so your compiler would have go back and forth between your references, but they do so in order. Choose the order of precedence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM