C ++静态const类成员初始化 [英] C++ static const class members initialization

查看:195
本文介绍了C ++静态const类成员初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个拥有 static 成员的类,但我不知道如何做。这是可能吗?

I'd like to have a class that has static members to itself, but I can't figure how to do that. Is that even possible?

我得到错误:


整数数据成员可以在类内初始化

only static const integral data members can be initialized within a class

代码:

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

        CData& operator = ( const CData& d );

        static const CData FIRST = CData( 512 ); //how?

    private:
        int data;
    };
}

当我使用 FIRST 很多我想使用 misc :: CData :: FIRST 静态访问它,而不需要在范围中的某处声明它。这是任何机会吗?

As I use FIRST a lot I would like to statically access it using misc::CData::FIRST without the need to declare it somewhere in the scope. Is that by any chance possible?

推荐答案


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

... 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 );
}

这篇关于C ++静态const类成员初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆