Why is it not possible to define a static member of a class in the main() function in C++?
C++ is a statically typed language. That is: the "shape" of all "things" (struct
, class
, functions, etc) must be known in-advance by the compiler (i.e. statically) - and due to historical reasons C++ requires all type-names and type-members to be declared and (excepting for member function bodies) defined ahead of time (that's what .h
files are for).
If programs were able to change the "shape" of something retroactively inside of a function then that would make it impossible for the compiler to know what the "shape" of a value is elsewhere in the program (well, this is what dynamically typed languages like JavaScript do, and it's why writing an AOT compiler for those is very hard).
An alternative approach, whereby the compiler does allow function implementations to define types is known as Hindley–Milner Type Inference, however C++ does not support it.
I note that the unsolvable problem with na?ve implementations of Hindley-Milner is that it's impossible for the compiler to determine if a referenced,
non-declared, member should count as a new declaration - or as an error: so given your program - if you were to fat-finger and type int A::B = 1;
instead of int A::b = 1
should the compiler give you an error or should it define B
in addition to b
? If it should give you an error how can it know if B
or b
should be the correct member?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…