Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

c++ - Why is it not possible to define a static (public) member of a class in the main() function?

Why is it not possible to define a static member of a class in the main() function in C++? Consider this code:

#include <iostream>
using namespace std;
class A
{
    public:
    int a;
    static int b;
    A()
    {
        // int A::b = 1;
    }
    void fun()
    {
        // int A::b = 1;
    }
};
int main() 
{
    A objA;
    int A::b = 1;
    return 0;
}

Output:

prog.cpp: In function ‘int main()’:
prog.cpp:20:14: error: qualified-id in declaration before ‘=’ token
     int A::b = 1;
              ^

But when I am trying to do the same outside of the main function, it is working. What is the reason for this?

question from:https://stackoverflow.com/questions/65871105/why-is-it-not-possible-to-define-a-static-public-member-of-a-class-in-the-main

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...