C++ 在哪里初始化静态常量 [英] C++ where to initialize static const

查看:30
本文介绍了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++ 在哪里初始化静态常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆