我有以下两个类:
具有构造函数 Foo(Bar*, int, int) 的 Foo(Bar*, int, int)
和调用新Foo的酒吧(this,int,int)
我认为在 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) ;
}
它应该看起来像这样(省略包括警卫):
福.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) { ... }
bar.cc
// Note: the opposite order would also work
#include "bar.h"
#include "foo.h"
Bar::Bar() {
new Foo(this, int, int);
}
如果从链接器获得"未定义的引用",则可能使用与定义签名不同的签名声明Foo::Foo
,或者根本没有定义它,或者没有链接到它编译到的对象文件。