了解如何正确治疗c++类常量

发布于 2024-10-31 16:34:10 字数 720 浏览 1 评论 0原文

考虑以下事项:

namespace MyNamespace{
class MyClass {
public:
   // Public area
private:
   // Private area
protected:
   // Protected area
}; /* Class */
} /* Namespace */

并考虑我想定义一个特定于我的类的常量。 我通常会执行以下操作:

namespace MyNamespace{
// Constants
const int MYINT = 12;
const std::string MYSTR = std::string("Hello");
// Class definition
class MyClass {
public:
   // Public area
private:
   // Private area
protected:
   // Protected area
}; /* Class */
} /* Namespace */

通过这种方式,我可以通过这种方式获取变量(在我的代码中的某个位置):

MyNamespace::MYINT;
MyNamespace::MYSTR;

这是一个好的做法吗?
考虑到可以通过多种方式处理常量(例如,通常使用枚举来处理数字常量),定义常量的最佳方法是什么(与类相关,但在某些地方也很有用)别的) ?

Consider the following:

namespace MyNamespace{
class MyClass {
public:
   // Public area
private:
   // Private area
protected:
   // Protected area
}; /* Class */
} /* Namespace */

And consider that I would like to define a constant which is specific for my class.
I usually do the following:

namespace MyNamespace{
// Constants
const int MYINT = 12;
const std::string MYSTR = std::string("Hello");
// Class definition
class MyClass {
public:
   // Public area
private:
   // Private area
protected:
   // Protected area
}; /* Class */
} /* Namespace */

In this way I can get my variable in this way (somewhere in my code):

MyNamespace::MYINT;
MyNamespace::MYSTR;

Is this a good practice?
Considering that constants can be treated in several ways (for example numeric constants are often treated using enum), what is the best approach to define a constant (related to a class, but that can be also useful somewhere else) ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

躲猫猫 2024-11-07 16:34:10

如果您想要特定于类的常量,并且还希望它们在您所说的其他地方(可能在类之外)有用,那么请将它们定义为 publicstatic 成员数据> 课程部分:

//.h file
class MyClass 
{
 public:
   //constants declarations
   static const int MYINT;
   static const std::string MYSTR;
};

//.cpp file
//constants definitions 
const int MyClass::MYINT = 12;
const std::string MyClass::MYSTR = std::string("Hello");

使用(或访问):

std::cout << MyClass::MYINT << std::endl;
std::cout << MyClass::MYSTR << std::endl;

输出:

12
Hello

在线演示: http://www.ideone.com/ 2xJsy


如果你想定义许多整型常量并且它们都以某种方式相关,你也可以使用 enum ,例如:

class shirt
{
 public:
   //constants declarations
   enum shirt_size
   {
        small, 
        medium,
        large,
        extra_large
   };
};

但是如果整型常量不相关,那么它就不会'在我看来,将它们定义为枚举没有多大意义。

If you want the constants specific to the class and also want them to be useful somewhere else as you said, possibly outside the class, then define them as static member data in the public section of the class:

//.h file
class MyClass 
{
 public:
   //constants declarations
   static const int MYINT;
   static const std::string MYSTR;
};

//.cpp file
//constants definitions 
const int MyClass::MYINT = 12;
const std::string MyClass::MYSTR = std::string("Hello");

Usage (or access):

std::cout << MyClass::MYINT << std::endl;
std::cout << MyClass::MYSTR << std::endl;

Output:

12
Hello

Online Demo: http://www.ideone.com/2xJsy


You can also use enum if you want to define many integral constants and all of them are somehow related, for example this:

class shirt
{
 public:
   //constants declarations
   enum shirt_size
   {
        small, 
        medium,
        large,
        extra_large
   };
};

But if the integral constants are not related, then it wouldn't make much sense to define them as enum, in my opinion.

我的痛♀有谁懂 2024-11-07 16:34:10

不存在“最佳”解决方案,因为这当然是一个非常主观的术语。

考虑到您提到在其他地方使用的常量,我们可以说它们应该在 protected 中声明(如果它们仅由派生类使用)或更可能在 public 中声明类的 部分。

非整数类型的常量应定义为 static const 成员(但您必须小心静态初始化的顺序(如果有任何其他静态对象引用这些常量)。

正如您已经提到的,整数类型的常量可以声明为 static const int 或枚举。这里的区别因素是两个或多个常数是否可以逻辑上分组在一起。

例如,这可能是一个好主意:

class MyClass {
    public:
        enum {
            Color_Red,
            Color_Green,
            Color_Blue,
        };
};

虽然这不是:

class MyClass {
    public:
        enum {
            Color_Red,
            Vehicle_Car,
        };
};

There is no "best" solution as of course that is a very subjective term.

Considering that you mention the constants being used somewhere else, we can say that they should be declared in either the protected (if they are to be used exclusively by derived classes) or more likely the public section of the class.

Constants that are not of integer type should be defined as static const members (but you will have to be careful of the order of static initialization if there are any other static objects that refer to these constants).

Constants of integer type can either be declared as static const int or as enums, as you already mention. The discriminating factor here is whether two or more constants can be logically grouped together.

For example, this is probably a good idea:

class MyClass {
    public:
        enum {
            Color_Red,
            Color_Green,
            Color_Blue,
        };
};

While this is not:

class MyClass {
    public:
        enum {
            Color_Red,
            Vehicle_Car,
        };
};
单挑你×的.吻 2024-11-07 16:34:10

我想定义一个特定于我的类的常量

如果该常量特定于该类,最好将其放在类本身中,而不是放在包含该类的命名空间中。

从 C++17 开始,我认为定义类常量的最佳方法(使用 内联变量< /a>) 是:

class MyClass 
{
public:
    // Constants declarations:
    static inline constexpr int MYINT = 12;
    static inline constexpr std::string MYSTR = "Hello";  // Use `const` instead of `constexpr` for C++17
};

static 意味着它有该类的一个副本(即它不是每个实例的成员)。
内联意味着它不需要单独的定义(带有初始化值)。
constexpr 表示它是一个编译时常量。

请注意,std::string 仅在 C++20 中具有 constexpr 构造函数。
如果您使用的是 C++17,则应将 MYSTR 更改为 const

现场演示

I would like to define a constant which is specific for my class

If the constant is specific to the class, it is best to put it in the class itself rather than in the namespace containing the class.

Since C++17 I think the best way of defining a class constant (using inline variables) is:

class MyClass 
{
public:
    // Constants declarations:
    static inline constexpr int MYINT = 12;
    static inline constexpr std::string MYSTR = "Hello";  // Use `const` instead of `constexpr` for C++17
};

static means it has one copy for the class (i.e. it's not a member per instance).
inline means it does not require a separate definition (with an initialization value).
constexpr means it is a compile time constant.

Note that std::string has a constexpr constructor only from C++20.
If you are using C++17 you should change it for MYSTR to const instead.

Live demo

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