Am I missing something here?

class Foo;

class Bar {
    public:
        Foo foo;
};

class Foo { };

Error:

error C2079: 'Bar::foo' uses undefined class 'Foo'

有帮助吗?

解决方案

When you forward-declare a class, you can make pointers and references to it, but you cannot make members of the type of forward-declared class: the full definition of Foo is needed to decide the layout of the outer class (i.e. Bar), otherwise the compiler cannot make a decision on the size and the structure of Bar.

This is allowed, though:

class Foo;

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

The reason the pointers and references to forward-declared classes are allowed is that the sizes of pointers and references do not depend on the structure of the class to which they point (or which they reference).

其他提示

Yes you are missing something important: A question.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top