C++ 中类特定命名常量的存储位置

发布于 2024-09-10 23:03:05 字数 672 浏览 3 评论 0原文

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

选项 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅语花开 2024-09-17 23:03:05

如果这些字符串是供类的用户查看/使用的,则您不会考虑将它们设为私有类成员。所以我得出的结论是,它们不应该被该类的用户看到/使用。但将它们放入标题中根本没有意义。

如果将它们放入类中(或放入标头的命名空间范围中),那么对其类型和标识符的所有更改都将强制客户端重新编译其代码。

如果将它们放入类的实现文件中,它们是类实现的私有细节,对它们的更改只会强制重新编译类的实现。
如果将它们放入未命名的命名空间,它们不能与任何其他名称冲突:

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

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";
  }
}
薄荷梦 2024-09-17 23:03:05

选项 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文