C ++在哪里初始化static const [英] C++ where to initialize static const
本文介绍了C ++在哪里初始化static const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类
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?
推荐答案
一个编译单元(通常是.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
是)如果它在代码中使用而不仅仅是整数常量表达式。详情请参阅David的评论。
(*) 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.
这篇关于C ++在哪里初始化static const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文