C++ where to initialize static const(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.
这篇关于C++ 在哪里初始化静态常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 在哪里初始化静态常量
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
