简体   繁体   English

为什么前向声明不适用于类?

[英]Why does forward declaration not work with classes?

int main() {
    B bb;                           //does not compile (neither does class B bb;)
    C cc;                           //does not compile

    struct t tt;                    //compiles

    class B {};                     //HERE is the class B defination
    struct s { struct t * pt; };    //compiles
    struct t { struct s * ps; };

    return 0;
}

class C {};

I just modified the example given here . 我刚修改了这里给出的例子。

Why is that the struct forward declarations work but not the class forward declarations? 为什么结构转发声明有效,而不是类前向声明​​?

Does it have something to do with the namespaces - tag namespace and typedef namespace ? 它是否与命名空间有关 - tag namespacetypedef namespace I know that the structure definitions without typedefs go to tag namespace. 我知道没有typedef的结构定义会转到标记命名空间。

Structures are just classes with all public members. 结构只是包含所有公共成员的类。 So, I expect them to behave similarly. 所以,我希望他们的行为类似。

Forward declaration works for classes, but other then you have expected. 前向声明适用于类,但其他时候你已经预期。 First, you have to write class B; 首先,你必须写class B; before the code of your main routine. 在你的main的代码之前。 Then you have to write B * bb; 然后你必须写B * bb; instead of B bb; 而不是B bb; . You can construct an object of type B only after class definition. 只能在类定义之后构造B类型的对象。

The reason for this behavior is as follows: The compiler does not know how many bytes it has to allocate on the stack for an instance of class B, as this information depends on the definition of the class (which you have not given at that time). 此行为的原因如下:编译器不知道它必须在堆栈上为B类实例分配多少字节,因为此信息取决于类的定义(当时您没有给出)。 A pointer to an instance of class B however can be constructed after a forward declaration of B, since the size of a pointer is previously known (and the normally the same for all pointer types). 然而,可以在B的前向声明之后构造指向类B的实例的指针,因为指针的大小是先前已知的(并且对于所有指针类型通常是相同的)。

Class forward declarations work fine; 班级前瞻性声明工作正常; you just didn't include one. 你只是没有包括一个。 Add

class B;

above the bb declaration and it'll work bb声明之上它会起作用

EDIT: As kibibu pointed out, you can't declare an incomplete type unless it's a pointer, so 编辑:正如kibibu指出的那样,你不能声明一个不完整的类型,除非它是一个指针,所以

B* bb;

would work, but your way wouldn't. 会工作,但你的方式不会。 Good call 好决定

I don't think the line "struct t tt;" 我不认为这行“struct t tt;” will compile. 将编译。

In C++, struct and class are the same except with different default access privileges. 在C ++中,struct和class是相同的,除了具有不同的默认访问权限。

Your line: 你的路线:

struct t tt;

Does not compile for me, I get: 不编译给我,我得到:

.\TestApp.cpp(11) : error C2079: 'tt' uses undefined struct 'main::t'

(This is Visual C++ 2008) (这是Visual C ++ 2008)

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

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