-1

次の2つのクラスがあります。

コンストラクター Foo(Bar*, int, int) を持つ Foo

new Foo(this, int, int) を呼び出す Bar

Bar.h で Foo および/または Foo.h で Bar を前方宣言すると、問題が解決すると想定しました。

(返されるエラーは、新しい Foo の「未定義の参照」です)

私はコンパイルにClangを使用しています。

そのままのリンク順序 (ただし、どちらの場合も同じエラーが発生します) は、Foo の次に Bar です。

私が間違っていることについて何か考えはありますか?

コードはおおよそ次のとおりです。残念ながら、実際のコードフラグメントを表示できません

  #include Bar.h 

 class Bar ; 

 class Foo { 
 public: 
 Foo(Bar* bar, int arg1, int arg2) ; 
 void method1()  {
     I access bar->field here
 }

Bar のコードは次のとおりです。

  #include Foo.h 



  class Bar { 
  public:

   Bar() { 
    Cache* cache = new Cache(this, 0, 0) ; 
  } 
4

1 に答える 1

1

次のようになります (インクルード ガードは省略します)。

foo.h

class Bar;

class Foo {
  public:
    Foo(Bar*, int, int);
};

bar.h

class Bar {
  public:
    Bar();
};

foo.cc

#include "foo.h"
// Note: no need to include bar.h if we're only storing the pointer

Foo::Foo(Bar*, int, int) { ... }

bar.cc

// Note: the opposite order would also work
#include "bar.h"
#include "foo.h"

Bar::Bar() {
  new Foo(this, int, int);
}

リンカーから「未定義の参照」を取得している場合は、Foo::Foo定義したものとは異なる署名で宣言したか、まったく定義していないか、コンパイル先のオブジェクト ファイルとリンクしていない可能性があります。

于 2012-12-14T21:44:23.903 に答える