简体   繁体   English

C ++类原型

[英]C++ Class Prototyping

Am I missing something here? 我在这里想念什么吗?

class Foo;

class Bar {
    public:
        Foo foo;
};

class Foo { };

Error: 错误:

error C2079: 'Bar::foo' uses undefined class 'Foo' 错误C2079:“ Bar :: foo”使用未定义的类“ 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 (ie Bar ), otherwise the compiler cannot make a decision on the size and the structure of Bar . 当您向前声明一个类时,可以创建它的指针和引用,但是不能使该类成为该成员的成员:需要Foo的完整定义来确定外部类的布局(即Bar ) ,否则编译器无法决定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. 编译器必须知道Foo的大小才能计算Bar类的布局。 The size of Foo objects is determined by their layout, to know that layout, the compiler has to know the class definition. Foo对象的大小由其布局确定,要知道该布局,编译器必须知道类定义。 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. 在声明成员变量foo时,它仅知道Foo存在,但不知道它的大小,因为您之前仅给它提供了一个声明,而不是定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM