C++中的循环依赖(?)

Rag*_*ava 4 c++ circular-dependency

我最初的怀疑是我的代码中存在循环依赖,并且通过Resolve头包含循环依赖.但这并没有解决我的编译错误.这是包含3个类的代码 - A,G和N.

//A.h

#ifndef A_H_
#define A_H_

class com::xxxx::test::G;

namespace com { namespace xxxx { namespace test {

class A {

public:
 A();
 ~A();
 void method1(void);

private:
 G* g;
};

} } }

#endif /* A_H_ */


//A.cpp

#include "A.h"
#include "G.h"

namespace com { namespace xxxx { namespace test {

A::A() {
 g = new com::xxxx::test::G();
}

A::~A() {
 delete g;
}

void A::method1() {
 g->method2(*this);
}

} } }


//G.h

#ifndef G_H_
#define G_H_

class com::xxxx::test::A;

namespace com { namespace xxxx { namespace test {

class G {
public:
 void method2(const A&);
};

} } }

#endif /* G_H_ */


//G.cpp

#include "N.h"

namespace com { namespace xxxx { namespace test {

void G::method2(const A& a) {
 N n(a, *this);
}

} } }


//N.h

#ifndef N_H_
#define N_H_

#include "A.h"
#include "G.h"

namespace com { namespace xxxx { namespace test {

class N {
public:
 N(const A& obj1, const G& obj2) : a(obj1), g(obj2) {}
 void method3(void);

private:
 A a;
 G g;
};

} } }

#endif /* N_H_ */
Run Code Online (Sandbox Code Playgroud)

我在Ah和A.cpp中得到大约10个编译错误我列出了下面的编译错误:

./src/A.h:11: error: 'com' has not been declared
../src/A.h:25: error: ISO C++ forbids declaration of 'G' with no type
../src/A.h:25: error: invalid use of '::'
../src/A.h:25: error: expected ';' before '*' token
../src/A.cpp: In constructor 'com::xxxx::test::A::A()':
../src/A.cpp:16: error: 'g' was not declared in this scope
../src/A.cpp: In destructor 'com::xxxx::test::A::~A()':
../src/A.cpp:20: error: 'g' was not declared in this scope
../src/A.cpp: In member function 'void com::xxxx::test::A::method1()':
../src/A.cpp:24: error: 'g' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

上面代码中的错误可能是什么?

提前谢谢你,
问候,
Raghava.

Pot*_*ter 9

前瞻性声明

 class com::xxxx::test::G;
Run Code Online (Sandbox Code Playgroud)

是非法的.必须在其中声明命名空间的成员.

namespace com { namespace xxxx { namespace test {
    class G;
Run Code Online (Sandbox Code Playgroud)

另外,正如Kenny所说,在C++中没有像这样使用命名空间.除非您的项目作为库分发或具有相当大的大小(最少几十个文件),否则您可能不需要自己的命名空间.


Fra*_*nov 5

当编译器尝试编译a.cop时,它遇到的第一件事(包含在啊)是这样的:

class com::xxxx::test::G;
Run Code Online (Sandbox Code Playgroud)

在这一点上,没有什么可以告诉编译器究竟是什么com,xxxx和test.这些中的每一个都可以是命名空间或类.这也意味着G不清楚,这会导致所有其他错误.