gpt4 book ai didi

C++静态常量类成员初始化

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:04 26 4
gpt4 key购买 nike

我想要一个自身具有static 成员的类,但我不知道该怎么做。这可能吗?

我得到错误:

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 静态访问它,而不需要在范围内的某个地方声明它。这有可能吗?

最佳答案

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

不,不声明它是不可能的(您已经在类声明中尝试这样做)。您的意思可能是,没有在您的类声明之外定义它。答案再次是否定的。
对于这种情况,您必须将声明和定义分开(它仅适用于原始整数类型,如 int 以直接在类声明中初始化它们)。

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

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

CData& operator = ( const CData& d );

static const CData& FIRST;

private:
int data;
};
}

然后在单独的编译单元中定义它(通常是CData.cpp)

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

关于C++静态常量类成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42324982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com