递归定义 [英] recursive definition in CPP
问题描述
我遇到这样的问题: UPDATE
class A
{
public:
A(){}
int i;
B b;
};
class B
{
public:
B(){}
int j;
A a;
};
当我在一个.h文件中定义它时,会给出一个错误。我认为问题是递归定义。但是有人可以帮我解决这个问题吗?
When I define it in one .h file, it would give an error. I think the problem is the recursive definition. But could someone help me how to solve such issue?
-
错误C2146: ;'before identifier'b'c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef
错误C4430:缺少类型说明符 - int。注意:C ++不支持default-int c:\users\xingyo\documents\visual studio 2010 \projects\cppalgo\recudef\test1.h 9 1 RecuDef
错误C4430:缺少类型说明符 - int。注意:C ++不支持default-int c:\users\xingyo\documents\visual studio 2010 \projects\cppalgo\recudef\test1.h 9 1 RecuDef
推荐答案
这在C ++中不可能逐字。解释是编译器需要完整的,而不仅仅是转发,一个类的声明,以便能够使用它作为另一个类的成员。它只需要一个类对象的大小。
This is not possible verbatim in C++. The explanation is that the compiler needs full, not just forward, declaration of a class to be able to use it as a member of another class. It simply needs the size of a class object.
C ++中的解决方法是使用或引用作为其中一个类的成员。这样你可以使用如下的前向声明:
The workaround in C++ (and in C) is to use a pointer or a reference as a member of one of the classes. That way you can use forward declaration as follows:
class A; // forward declaration
class B {
// ...
A* pa;
};
class A { // full declaration
// ...
B b;
};
这是你(不是编译器或运行时)负责保持 A
的实例 B
指向(或引用)有效。
It's your (not the compiler or runtime) responsibility to keep the instance of A
that instance of B
points to (or references) valid.
这篇关于递归定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!