类中的静态字符串常量与常量的命名空间 [c++] [英] static string constants in class vs namespace for constants [c++]

查看:31
本文介绍了类中的静态字符串常量与常量的命名空间 [c++]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I want to declare string constants that will be used across various classes in the project. I am considering two alternatives

Option 1:

#header file 
class constants{
    static const string const1;
};

#cpp file

const string constants::const1="blah";

Option 2:

#header file 
namespace constants{
    static const string const1="blah";
};

Just wondering what would be a better implementation.

Already looked at

Where to store Class Specific named constants in C++

Where to put constant strings in C++: static class members or anonymous namespaces


UPDATE:

Option 3:

Based on the suggestions from "potatoswatter" and "sellibitze" i currently have the following implementation?

#header file
namespace constants{
    extern const string& const1(); //WORKS WITHOUT THE EXTERN  ***WHY***
};

#cpp file
namespace constants{
   const string& const1(){static string* str = new string ("blah"); return *str;}
}

I'm including the header file where i need to use the constants. Are there any major cons of this implementation?

解决方案

Update 2 years later:

Every global accessible by more than one source file should be wrapped in an inline function so the linker shares the object between the files, and the program initializes it properly.

inline std::string const &const1() {
    static std::string ret = "hello, world!";
    return ret;
}

The inline function is implicitly extern and may be wrapped in a named namespace or a class, if you like. (But don't use a class just to hold static members, as namespaces are better for that. And don't use an anonymous namespace as that would defeat the linker, and each source would see a different std::string object.)

这篇关于类中的静态字符串常量与常量的命名空间 [c++]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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