在C ++中存储类特定命名常量的地方

编程入门 行业动态 更新时间:2024-10-09 08:28:04
本文介绍了在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 ++中存储类特定命名常量的地方

本文发布于:2023-11-25 17:58:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630757.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   地方

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!