在C ++中存储类特定命名常量的地方 [英] Where to store Class Specific named constants in C++

查看:177
本文介绍了在C ++中存储类特定命名常量的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个类有一些命名的常量,什么是存储常量的最佳实践:

If you have a class that has some named constants, what is the best practive for storing the constants:

选项1: / strong>

Option 1: Namespace in Class header

在我的类头中,我将有:

So in my class header I will have:

class myClass
{
...
...
};

namespace NamedConstants
{
   const string Bucket = "Bucket";
}

选项2成员常数 b
$ b

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";






我实际上更喜欢选项1, clean:变量名和值一起出现。此外,如果你给命名空间一个好的名称,那么它可以使代码更可读时,你使用常量:


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

有没有人通过选项2看到此方法的任何问题?

Does anybody see any issue with this method over Option 2?

推荐答案

如果字符串被类的用户看到/使用,你不会考虑让他们 private 类成员。所以我得出结论,他们不是要被类的用户看到/使用。但是,把它们放在标题中没有意义。

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:

namespace  {
  namespace NamedConstants
  {
     const string Bucket = "Bucket";
  }
}

这篇关于在C ++中存储类特定命名常量的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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