最佳实践 - 应该在哪里定义 class 的 const 数据
best practice - where should const data for the class should be defined
我写了一个 class 定义和使用 const string
(此字符串定义路径或路径的一部分)
我应该在哪里定义它:在 cpp 或 h 中?它应该是 class 的一部分吗?
目前此数据仅在内部成员函数中使用。
哪个选项更好?
myClass.h
// const std::string PATH = "Common\Data\input.txt" (1)
class MyClass
{
public:
// const std::string m_path = "Common\Data\input.txt" (2)
private:
// const std::string m_path = "Common\Data\input.txt" (3)
}
myClass.cpp
// const std::string PATH = "Common\Data\input.txt"(4)
如果此常量仅在一个 class 中使用,并且对 class 的所有实例都相同,您可以在 .cpp 文件的 unnamed namespace 中定义它:
namespace {
const std::string PATH = "Common\Data\input.txt";
}
这样,它将只能在单个 .cpp 文件中访问,并且如果任何其他文件定义了类似的变量,则在链接期间不会导致任何潜在的名称冲突。
这种方法的主要目标是使用尽可能小的定义范围来减少冗余的隐式依赖。例如,如果此常量发生更改,您的 class 的客户端将不必重新编译。
I write a class which defines and uses const string (This string defines a path or a part of the path) Where should I define it : in cpp or h?
视情况而定。
对于 class 的所有实例,string m_path
的值是否相同?
- 如果是,那么它应该是
static const
,或者只是全局定义或在“.cpp”文件中未命名的命名空间中定义。
对于 class 的每个/某些实例,string m_path
的值是否不同?
- 如果是,那么应该是
private
const
数据成员,在构造函数中初始化
For now this data is used only inside internal member functions which option is better?
那么应该是private
,而不是public
。
我写了一个 class 定义和使用 const string
(此字符串定义路径或路径的一部分)
我应该在哪里定义它:在 cpp 或 h 中?它应该是 class 的一部分吗?
目前此数据仅在内部成员函数中使用。
哪个选项更好?
myClass.h
// const std::string PATH = "Common\Data\input.txt" (1)
class MyClass
{
public:
// const std::string m_path = "Common\Data\input.txt" (2)
private:
// const std::string m_path = "Common\Data\input.txt" (3)
}
myClass.cpp
// const std::string PATH = "Common\Data\input.txt"(4)
如果此常量仅在一个 class 中使用,并且对 class 的所有实例都相同,您可以在 .cpp 文件的 unnamed namespace 中定义它:
namespace {
const std::string PATH = "Common\Data\input.txt";
}
这样,它将只能在单个 .cpp 文件中访问,并且如果任何其他文件定义了类似的变量,则在链接期间不会导致任何潜在的名称冲突。
这种方法的主要目标是使用尽可能小的定义范围来减少冗余的隐式依赖。例如,如果此常量发生更改,您的 class 的客户端将不必重新编译。
I write a class which defines and uses const string (This string defines a path or a part of the path) Where should I define it : in cpp or h?
视情况而定。
对于 class 的所有实例,string m_path
的值是否相同?
- 如果是,那么它应该是
static const
,或者只是全局定义或在“.cpp”文件中未命名的命名空间中定义。
对于 class 的每个/某些实例,string m_path
的值是否不同?
- 如果是,那么应该是
private
const
数据成员,在构造函数中初始化
For now this data is used only inside internal member functions which option is better?
那么应该是private
,而不是public
。