希望在某个中心点定义常量(例如某些字符串或数字)。为了保持代码的可读性,还希望能够轻松访问这些常量。在我研究实现这一目标的良好做法的过程中,我现在找到了以下两个解决方案 ( 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?
是的,有。我可以看到两个:
使用类解决方案,您可以控制可访问性(
public
/protected
/private
),这在命名空间解决方案中是不可能的.使用命名空间,您可以将声明拆分到多个文件中,而类解决方案无法做到这一点,因为类定义(包含所有成员的声明)必须在单个文件中给出。
关于c++ - extern const inside namespace 和 static const 类成员之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18787042/