4

我最初的怀疑是我的代码中存在循环依赖,并通过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_ */

我在 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

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

提前谢谢你,
问候,
拉加瓦。

4

4 回答 4

9

前向声明

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

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

namespace com { namespace xxxx { namespace test {
    class G;

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

于 2010-08-28T08:19:31.183 回答
5

当编译器尝试编译 a.cop 时,它遇到的第一件事(包括来自 ah)是这样的:

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

此时,没有什么可以告诉编译器 com、xxxx 和 test 到底是什么。其中每一个都可以是命名空间或类。这也意味着 G 不清楚,从而导致所有其他错误。

于 2010-08-28T08:29:42.893 回答
2

class com::xxxx::test::G;在 C++ 中合法吗?我会写:

namespace com {
   namespace xxxx {
       namespace test {
          class G;
       }
   }
}
于 2010-08-28T08:20:16.347 回答
2

正如其他人指出的那样,使用class com::xxxx::test::G;是非法的。

更简单的转换是(保持内联性):

namespace com { namespace xxxx { namespace test { class G; } } }

我更喜欢这种前向声明的方式,因为“grepping”不显示范围,而这种语法立即将其展示给所有人看。

于 2010-08-28T14:16:36.000 回答