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. Is there a way to "predefine" a class? Like Objective-C's @class macro?
我在做一个游戏,我有一个类,叫做Man,一个类,在他们的代码中叫做Block,它们都需要彼此,但它们都在分离的文件中。是否有一种方法来“预先定义”一个类?objective - c的@class宏?
2 个解决方案
#1
5
It's called a circular dependency. In class Two.h
这叫做循环依赖。在课堂上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; 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:
“类1;”和“类2;”指令分别分配一个类名“1”和“2”;但除了名字之外,他们没有定义任何其他细节。因此你可以创建类的指针,但是你不能像这样包含整个类:
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.
上面这两个示例无法编译的原因是,尽管编译器知道有一个类1,但它不知道类1可能包含哪些字段、方法或虚拟方法,因为只有名称被定义,而不是实际的类定义。
#2
11
Yes.
是的。
class Man;
This will declare Man
as an "incomplete type". 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.
这将宣告人是“不完整的类型”。可以声明指向它的指针或引用以及其他一些东西,但是不能创建实例或访问它的成员。这并不是对不完整类型所能做和不能做的完整描述,但这是总的思想。
#1
5
It's called a circular dependency. In class Two.h
这叫做循环依赖。在课堂上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; 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:
“类1;”和“类2;”指令分别分配一个类名“1”和“2”;但除了名字之外,他们没有定义任何其他细节。因此你可以创建类的指针,但是你不能像这样包含整个类:
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.
上面这两个示例无法编译的原因是,尽管编译器知道有一个类1,但它不知道类1可能包含哪些字段、方法或虚拟方法,因为只有名称被定义,而不是实际的类定义。
#2
11
Yes.
是的。
class Man;
This will declare Man
as an "incomplete type". 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.
这将宣告人是“不完整的类型”。可以声明指向它的指针或引用以及其他一些东西,但是不能创建实例或访问它的成员。这并不是对不完整类型所能做和不能做的完整描述,但这是总的思想。