gpt4 book ai didi

c++ - 了解如何正确对待 c++ 类常量

转载 作者:IT老高 更新时间:2023-10-28 23:11:21 32 4
gpt4 key购买 nike

考虑以下几点:

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

考虑到我想定义一个特定于我的类(class)的常量。我通常会这样做:

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;

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

谢谢

最佳答案

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

//.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
};
};

但如果整数常量不相关,那么在我看来,将它们定义为 enum 就没有多大意义。

关于c++ - 了解如何正确对待 c++ 类常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5620256/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com