且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++静态const类成员初始化

更新时间:2021-12-28 00:17:56


...无需声明它在某处范围。

... without the need to declare it somewhere in the scope. Is that by any chance possible?

不,没有声明它是不可能的(你已经在你的类声明中尝试过) 。你可能不需要在类声明之外定义 。同样的答案是否定的。

你必须为这种情况分离声明和定义(它只适用于原始的整数类型,如 int ,直接初始化在类声明中)。

No, it's not possible without declaring it (which you already tried to do in your class declaration). You probably meant, without defining it outside your class declaration. Again the answer is no.
You have to separate declaration and definition for this case (it only works with primitive integral types like int to initialize these directly in the class declaration).

首先在类声明中有一个简单的声明(通常是 CData.hpp

First have a simple declaration in your class declaration (usually something like CData.hpp)

namespace misc {
    class CData {
    public:
        CData( ) { };
        CData( int d );

        CData& operator = ( const CData& d );

        static const CData& FIRST;

    private:
        int data;
    };
}

,然后在单独的编译单元$ c> CData.cpp )

and then define it in a separate compilation unit (usually something like CData.cpp)

namespace misc {
    const CData& CData::FIRST = CData( 512 );
}