Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Why do non-const, non-int/enum static data members have to be initialized outside the definition?

I understand that only data members which are static, const and int/enum (pre c++11) can be initialized inside the class declaration. "All other static data members must be defined at global namespace scope (i.e. outside the body of the class definition) and can be only initialized in those definitions".

Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?

If the data members are specific to the class, why are they declared at the global namespace scope and not some scope relevant to their class?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?

Most likely because C++ has separate translation units. The compiler needs to pick an object file where the initialization logic for those symbols will be placed. Forcing this to be in a specific source file makes that decision easy for the compiler.

If the data members are specific to the class, why are they declared at the global namespace scope and not some scope relevant to their class?

Because that's just how C++ does class members. This is no different than other class members like member functions:

Header file:

namespace example {

// Class declared in header
struct some_class
{
    // Member variable
    static float example;
    // Member function
    void DoStuff() const;
};

}

Source file:

namespace example {

    // Implement member variable
    float some_class::example = 3.14159;
    // Implement member function
    void some_class::DoStuff() const
    {
         //....
    }
}

There's a specific exception to allow static const integral members to be initialized in the header because it allows the compiler to treat them as compile-time constants. That is, you can use them to define sizes of arrays or other similar bits in the class definition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...