-1

我有以下两个课程:

Foo 具有构造函数 Foo(Bar*, int, int)

和 Bar 调用 new Foo(this, int, int)

我认为在 Bar.h 中前向声明 Foo 和/或在 Foo.h 中声明 Bar 可以解决问题。

(返回的错误是 new 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);
};

酒吧.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) { ... }

酒吧.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 回答