简体   繁体   English

C ++在一个标头中声明多个类

[英]C++ declaring multiple classes in one header

I got an assignment where I am supposed to create a Linked list by using CRTP. 我有一个作业,应该使用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 清单.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; 现在我的问题是关于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. 我做了一些实验,意识到如果没有类定义,Link.h就不会被编译,这是因为friend class List<T>语句的缘故。 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? 但是,为什么我不能只编写#include "List.h"并删除List.h内部的继承并从一开始就使用该定义呢? 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 清单.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. 您的.h文件似乎相互镜像,因此您的编译器本可以在引用之间来回移动,但它们是按顺序进行的。 Choose the order of precedence. 选择优先顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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