简体   繁体   English

C ++:两个需要彼此的类

[英]C++: Two classes needing each other

I'm making a game and I have a class called Man and a class called Block in their code they both need each other, but they're in seperate files. 我正在制作一个游戏,我在他们的代码中有一个名为Man的类和一个名为Block的类,它们都需要彼此,但它们都是单独的文件。 Is there a way to "predefine" a class? 有没有办法“预定义”一个班级? Like Objective-C's @class macro? 像Objective-C的@class宏?

Yes. 是。

class Man;

This will declare Man as an "incomplete type". 这将声明Man为“不完整类型”。 You can declare pointers or references to it and a few other things, but you can't create an instance or access members of it. 您可以声明指针或对它的引用以及其他一些内容,但是您无法创建实例或访问它的成员。 This isn't a complete description of what you can and can't do with an incomplete type, but it's the general idea. 这不是对不完整类型可以做什么和不可做什么的完整描述,但这是一般的想法。

It's called a circular dependency. 它被称为循环依赖。 In class Two.h 在Class Two.h中

class One;

class Two {
  public:
    One* oneRef;
};

And in class One.h 在One.h课程中

class Two;

class One {
  public:
    Two* twoRef;
};

The "class One;" “一级;” and "class Two;" 和“二级;” directives allocate a class names "One" and "Two" respectively; 指令分别分配一个类名“One”和“Two”; but they don't define any other details beyond the name. 但他们没有定义名称之外的任何其他细节。 Therefore you can create pointers the class, but you cannot include the whole class like so: 因此,您可以在类中创建指针,但不能像这样包含整个类:

class One;

class Two : public One {
};

class Three {
  public:
    One one;
};

The reason the two examples above won't compile is because while the compiler knows there is a class One, it doesn't know what fields, methods, or virtual methods, class One might contain because only the name had been defined, not the actual class definition. 上面两个例子不能编译的原因是因为虽然编译器知道有一个类,但它不知道一类可能包含哪些字段,方法或虚方法,因为只定义了名称,而不是实际的类定义。

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

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