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

2022-01-05 00:00:00 initialization static constants c++

我有一堂课

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

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

Where is the best place to initialize the string s in the source file?

推荐答案

one 编译单元(通常是 .cpp 文件)中的任何位置都可以:

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

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;

(*) 根据标准,如果 i 用于除整数常量表达式以外的代码,则必须在类定义之外定义它(如 j 是).详情请参阅下面大卫的评论.

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

相关文章