c++ - extern const inside namespace 和 static const 类成员之间的区别?

标签 c++ static constants extern

希望在某个中心点定义常量(例如某些字符串或数字)。为了保持代码的可读性,还希望能够轻松访问这些常量。在我研究实现这一目标的良好做法的过程中,我现在找到了以下两个解决方案 ( https://stackoverflow.com/a/9649425/2776093 )。

FoodConstants.h:

namespace FoodConstants {
    namespace Fruits {
        extern const string Apple;
        ...
    }
    ...
}

FoodConstants.cpp:

namespace FoodConstants {
    namespace Fruits {
        const string Apple = "apple" ;
        ...
    }
    ...
}

FoodConstants2.h:

class FoodConstants {
public:
    class Fruits {
    public:
        static const string Apple;
        ...
    }
    ...
}

FoodConstants2.cpp:

const string FoodConstants::Fruits::Apple = "apple"
...

对于这两种解决方案,我都可以在程序中包含 .h 的任何位置使用 FoodConstants::Fruits::Apple 访问 apple 常量。初始化在同一个编译单元中完成,避免了初始化问题。我注意到一个区别:对于第二种解决方案,我不能,例如,做一个“使用命名空间 FoodConstants”来缩写对字符串常量的访问 Fruits::Apple。

还有其他区别吗?有没有更好的方式来组织像这样的常量?

最佳答案

Are there any other differences?

是的,有。我可以看到两个:

  1. 使用类解决方案,您可以控制可访问性(public/protected/private),这在命名空间解决方案中是不可能的.

  2. 使用命名空间,您可以将声明拆分到多个文件中,而类解决方案无法做到这一点,因为类定义(包含所有成员的声明)必须在单个文件中给出。

关于c++ - extern const inside namespace 和 static const 类成员之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18787042/

相关文章:

c++ - 您使用#pragma 编写的哪些代码有用?

c++ - 使用 reinterpret_cast 变量赋值后可能的析构函数?

c++ - 运行 g++ 应用程序时出错。 (字符串加密)

C# const 结构列表

.net - 为什么默认情况下文字不是 const ?

c++ - gcc上静态成员变量编译错误的概念检查

c++ - 如何在 C++ 中重载运算符 [ ]?

java - 是否需要在同一个类中创建一个类的对象?

python - 有没有办法在创建类(不是实例)时调用(静态)方法?

java - Java 中的构造函数调用