C++ 中类特定命名常量的存储位置
如果您有一个包含一些命名常量的类,那么存储常量的最佳实践是什么:
选项 1:类标头中的命名空间
因此,在我的类标头中,我将具有:
class myClass
{
...
...
};
namespace NamedConstants
{
const string Bucket = "Bucket";
}
选项 2 成员常量
class MyClass { // this goes in the class
private: // header file
static const string Bucket;
...
};
...以及在类实现文件中:
const string MyClass::Bucket = "Bucket";
我实际上更喜欢选项 1,认为它更清晰:变量名称和值出现在一起。另外,如果你给命名空间一个好名字,那么当你使用常量时,它可以使代码更具可读性:
TrafficLight::Green
有人认为这个方法相对于选项 2 有什么问题吗?
If you have a class that has some named constants, what is the best practive for storing the constants:
Option 1: Namespace in Class header
So in my class header I will have:
class myClass
{
...
...
};
namespace NamedConstants
{
const string Bucket = "Bucket";
}
Option 2 Member Constants
class MyClass { // this goes in the class
private: // header file
static const string Bucket;
...
};
... and in the class implementation file:
const string MyClass::Bucket = "Bucket";
I actually prefer Option 1, considering it to be cleaner: the variable name and value appear together. Also, if you give the namespace a good name then it can make code more readable when you use constants:
TrafficLight::Green
Does anybody see any issue with this method over Option 2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这些字符串是供类的用户查看/使用的,则您不会考虑将它们设为
私有
类成员。所以我得出的结论是,它们不应该被该类的用户看到/使用。但将它们放入标题中根本没有意义。如果将它们放入类中(或放入标头的命名空间范围中),那么对其类型和标识符的所有更改都将强制客户端重新编译其代码。
如果将它们放入类的实现文件中,它们是类实现的私有细节,对它们的更改只会强制重新编译类的实现。
如果将它们放入未命名的命名空间,它们不能与任何其他名称冲突:
If the strings are meant to be seen/used by users of the class, you wouldn't consider to make them
private
class members. So I conclude they are not meant to be seen/used by users of the class. But then it doesn't make sense to put them into the header at all.If you put them into the class (or into namespace scope into the header), then all changes to their type and identifier will force clients to recompile their code.
If you put them into the class' implementation file, they are a private detail of the class' implementation and changes to them only force recompilation of the class' implementation.
If you put them into an unnamed namespace, they cannot collide with any other name:
选项 1 可能会为每个包含标头的文件生成一个单独的字符串对象。因此,这取决于您的资源稀缺程度。
Option 1 could lead to a separate string object for every file which includes the header. So it depends among others on how scarce your resources are.