甚至在创建该类之前声明对象 [英] Declare an object even before that class is created
问题描述
在C ++中创建类之前,有没有声明一个类的对象?我问,因为我试图使用两个类,第一个需要有一个其中的第二个类的实例,但第二个类也包含第一个类的实例。我意识到你可能认为我可能进入一个无限循环,但我实际上需要在第一个类之前创建和实例的第二个类。
Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.
推荐答案
你不能这样做:
class A {
B b;
};
class B {
A a;
};
最明显的问题是编译器不知道如何大型需要做类A,因为B的大小取决于A的大小!
The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!
但是,你可以这样做:
class B; // this is a "forward declaration"
class A {
B *b;
};
class B {
A a;
};
将B类声明为前向声明允许您使用指针(和引用)具有整个类定义。
Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.
这篇关于甚至在创建该类之前声明对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!