C++ 在哪里初始化静态常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2605520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:03:36  来源:igfitidea点击:

C++ where to initialize static const

c++staticinitializationconstants

提问by Thomas

I have a class

我有一堂课

class foo {
public:
   foo();
   foo( int );
private:
   static const string s;
};

Where is the best place to initialize the string sin the source file?

s源文件中初始化字符串的最佳位置在哪里?

回答by squelart

Anywhere in onecompilation unit (usually a .cpp file) would do:

一个编译单元(通常是 .cpp 文件)中的任何地方都可以:

foo.h

foo.h

class foo {
    static const string s; // Can never be initialized here.
    static const char* cs; // Same with C strings.

    static const int i = 3; // Integral types can be initialized here (*)...
    static const int j; //     ... OR in cpp.
};

foo.cpp

文件

#include "foo.h"
const string foo::s = "foo string";
const char* foo::cs = "foo C string";
// No definition for i. (*)
const int foo::j = 4;

(*) According to the standards you must define ioutside of the class definition (like jis) if it is used in code other than just integral constant expressions. See David's comment below for details.

(*) 根据标准,如果在代码中使用而不仅仅是整数常量表达式,则必须i在类定义之外进行定义(如jis)。有关详细信息,请参阅下面大卫的评论。

回答by Michael Burr

Static members need to be initialized in a .cpp translation unit at file scope or in the appropriate namespace:

静态成员需要在文件范围或适当命名空间的 .cpp 翻译单元中初始化:

const string foo::s( "my foo");

回答by GManNickG

In a translation unit within the same namespace, usually at the top:

在同一命名空间内的翻译单元中,通常位于顶部:

// foo.h
struct foo
{
    static const std::string s;
};

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
{
    struct bar
    {
        static const float f;
    };
}

// bar.cpp
namespace baz
{
    const float bar::f = 3.1415926535;
}

回答by plexando

Since C++17 the inlinespecifier also applies to variables. You can now define static member variables in the class definition:

从 C++17 开始,内联说明符也适用于变量。您现在可以在类定义中定义静态成员变量:

#include <string>

class foo {
public:
   foo();
   foo( int );
private:
   inline static const std::string s { "foo" };
};

回答by Behnam Dezfouli

Only integral values (e.g., static const int ARRAYSIZE) are initialized in header file because they are usually used in class header to define something such as the size of an array. Non-integral values are initialized in implementation file.

只有整数值(例如,static const int ARRAYSIZE)在头文件中初始化,因为它们通常在类头中用于定义诸如数组大小之类的内容。非整数值在实现文件中初始化。