CPP中的递归定义

时间:2010-11-29 02:29:49

标签: c++

我遇到了这样的问题:更新

class A
{
public:
    A(){}
    int i;
    B b;
};

class B
{
public:
    B(){}
    int j;
    A a;
};

当我在一个.h文件中定义它时,会出错。我认为问题是递归定义。但有人可以帮我解决这个问题吗?

  1. error C2146: syntax error : missing ';' before identifier 'b' c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef

  2. error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef

  3. error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef

5 个答案:

答案 0 :(得分:11)

这在C ++中不可能逐字逐句。解释是编译器需要完整的,而不仅仅是前向的类声明才能将它用作另一个类的成员。它只需要类对象的大小

C ++(以及C语言)中的解决方法是使用指针引用作为其中一个类的成员。这样你可以使用前向声明如下:

class A; // forward declaration

class B {
    // ...
    A* pa;
};

class A { // full declaration
    // ...
    B b;
};

保持A实例B指向(或引用)的实例有效,这是您的(不是编译器或运行时)责任。

答案 1 :(得分:4)

你无法解决它。这毫无意义。你已经定义A包含B,其中包含另一个A,其中包含另一个B ......你不可能有这个意图。也许你需要使用指针或引用?

答案 2 :(得分:0)

如果是递归问题。声明没有定义的类:

class A;
class B;

class A
{
   ...
};

class B
{
   ...
};

请参阅:http://www.gotw.ca/gotw/034.htm

答案 3 :(得分:0)

将代码分成4个文件,比如A.h,A.cpp,B.h和B.cpp。

// A.h

class B;
class A {
public:
    A();
    B* b;
};

// A.cpp

#include "A.h"
#include "B.h"

A::A() : b(new B) {
}

// B.h

class A;
class B {
public:
    B(A* a_);
    A* a;
};

// B.cpp

#include "B.h"
#include "A.h"

B::B(A* a_) : a(a_) {
}

以这种方式使用它们:

#include "A.h"
#include "B.h"

int main() {
    A a;
    B b(&a);

    // do logics

    return 0;
}

答案 4 :(得分:0)

你不能在C ++中有这样的递归定义。在声明class A的对象之前,必须完全定义A,以便编译器知道sizeof(A)。与B相同。但是,您可以使用指针绕过它。您可以通过简单地“承诺”在稍后的某个时间定义class A来声明指向class A对象的指针。这称为前向声明

class B;  // forward declaration

class A
{
  B *b;
};

class B
{
  A *a;
};

前向声明也适用于参考。