【发布时间】:2023-03-13 04:36:01
【问题描述】:
可能重复:
Why is a class allowed to have a static member of itself, but not a non-static member?
这是一段无效的代码
struct a{
a mem; //Invalid as the compiler does not know how much memory to allocate
};
但这是有效的:
class Date{
int d,m,y;
static Date Default_date; //Valid
};
在 Date 数据类型没有正确定义之前,编译器如何知道这里要分配多少内存!!
这在某种意义上和其他静态定义有区别吗???
【问题讨论】:
-
当您声明静态成员时,编译器无法知道 Date 有多大。但是想一想——它现在不需要知道它。
-
我猜编译器不会为那里的静态变量分配内存(然后在类内部),但是当它被声明时。例如字段,它必须在声明时知道类型本身的大小。我认为它可能由编译器完成(我不知道他们没有)而不需要太多努力,我想编译器大师会来解释......