我需要在一个与类相关且不会在类外部使用的cpp
文件中使用一些常量值。
我想到了几种方法:
方法1:.cpp
文件中的static const
static const int a = 100; // <<<
int Class::foo() const
{
return a + 10;
}
int Class::bar() const
{
return a - 10;
}
如果我理解正确,我也可以省略static
关键字,因为在这种情况下const
自动暗示了内部链接。
如果我理解有误,请纠正我。
方法2:匿名命名空间(C++11)
基本上和之前的方法一样,但是:
namespace
{
const int a = 100;
}
我相信这种方法是在C++11之前声明此类作用域常量的首选方式。
如果我错了,请再次纠正我。
方法三:.h
文件中的static const
class Class
{
public:
int foo() const;
int bar() const;
protected:
static const int a = 100; // <<<
};
Method 4: non-static const
in .h
(C++11)
class Class
{
public:
int foo() const;
int bar() const;
protected:
const int a = 100; // <<<
};
或者像这样:const int a{100}
。我认为对于POD类型没有区别。
再次强调,如果我说错了,请纠正我。
方法5:初始化列表
class Class
{
public:
Class() : a(100) {} // <<<
int foo() const;
int bar() const;
protected:
const int a;
};
总结
我认为不应该使用方法1和2,因为如果我需要创建子类,它们将失败。
此外,如果有许多重载的构造函数,我认为方法5将很难维护。
虽然这个问题可能被认为是基于观点的,但主要是我试图弄清楚这些方法的优缺点,可能还有其他可能的解决方案。
sizeof(int)
增加了类的大小。 - undefinedstatic constexpr
会更好。 - undefined