1

我在这里错过了什么吗?

class Foo;

class Bar {
    public:
        Foo foo;
};

class Foo { };

错误:

错误 C2079:“Bar::foo”使用未定义的类“Foo”

4

2 回答 2

8

当你前向声明一个类时,你可以对它进行指针和引用,但你不能创建前向声明类的类型的成员:需要完整的定义Foo来决定外部类的布局(即Bar),否则编译器无法决定Bar.

但是,这是允许的:

class Foo;

class Bar {
    public:
        Foo* fooPtr;
        Foo& fooRef;
};

允许指向前向声明的类的指针和引用的原因是指针和引用的大小不依赖于它们指向(或它们引用)的类的结构。

于 2013-02-28T08:19:02.930 回答
0

是的,你错过了一些重要的东西:一个问题。

I assume you want to know what's wrong in the code, and why the compiler issues an error.

The compiler has to know the size of Foo in order to calculate the layout of the class Bar. The size of Foo objects is determined by their layout, to know that layout, the compiler has to know the class definition. At the point where you declare the Member variable foo, it merely knows that Foo exists, but not its size, because you have given it only a declaration, not a definition before.

于 2013-02-28T08:19:38.343 回答