简体   繁体   English

命名空间内的extern const与静态const类成员之间的区别?

[英]Difference between extern const inside namespace and static const class member?

It is desirable to have constants (eg certain strings or numbers) to be defined at some central point. 希望在某个中心点定义常量(例如某些字符串或数字)。 In order to keep readability of the code well, it is also desirable have easy access to those constants. 为了很好地保持代码的可读性,还希望易于访问那些常量。 During my research for good practices to achieve this I have now found the following two solutions ( https://stackoverflow.com/a/9649425/2776093 ). 在研究实现这一目标的良好做法的过程中,我现在发现了以下两个解决方案( https://stackoverflow.com/a/9649425/2776093 )。

FoodConstants.h: FoodConstants.h:

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

FoodConstants.cpp: FoodConstants.cpp:

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

FoodConstants2.h: FoodConstants2.h:

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

FoodConstants2.cpp: FoodConstants2.cpp:

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

For both solutions I can access the the apple constant with FoodConstants::Fruits::Apple anywhere in the program where the .h is included. 对于这两种解决方案,我都可以使用FoodConstants :: Fruits :: Apple在程序中包含.h的任何位置访问apple常量。 Initialization is done in the same compilation unit and initialization problems are avoided. 初始化在同一编译单元中完成,避免了初始化问题。 I have noticed one difference: For the second solution I can't, eg, do a "using namespace FoodConstants" to abbreviate the access to the string constant with Fruits::Apple. 我注意到一个区别:对于第二个解决方案,我无法执行“使用名称空间FoodConstants”来简化对Fruits :: Apple的字符串常量的访问。

Are there any other differences? 还有其他区别吗? Is there a preferred way to organize constants like this? 有没有组织这种常量的首选方法?

Are there any other differences? 还有其他区别吗?

Yes, there are. 是的,有。 I can see two: 我可以看到两个:

  1. Using the class solution you can control accessibility ( public / protected / private ) which is not possible with the namespace solution. 使用类解决方案,您可以控制名称空间解决方案无法实现的可访问性( public / protected / private )。

  2. Using namespace you can split the declarations across several files while this is not possible with the class solution since the class definition (which contains the declarations of all members) must be given in a single file. 使用名称空间,您可以将声明分成多个文件,而对于类解决方案则无法做到,因为类定义(包含所有成员的声明)必须在单个文件中给出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM