4

私の最初の疑いは、コードに循環依存関係があり、Resolve ヘッダーが循環依存関係を含むということでした。しかし、これは私のコンパイルエラーを解決していません. これは、A、G、および N の 3 つのクラスを含むコードです。

//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 に答える