2007-09-06

如何在类中定义常量?

关键字: bs voice

如果你想得到一个可用于常量表达式中的常量,例如数组大小的定义,那么你有两种选择:

	class X {
static const int c1 = 7;
enum { c2 = 19 };

char v1[c1];
char v2[c2];

// ...
};
一眼望去,c1的定义似乎更加直截了当,但别忘了只有static const的整型或枚举型量才能如此初始化。这就很有局限性,例如:
	class Y {
const int c3 = 7; // error: not static
static int c4 = 7; // error: not const
static const float c5 = 7; // error not integral
};
我还是更喜欢玩“enum戏法”,因为这种定义可移植性好,而且不会引诱我去使用非标准的“类内初始化”扩展语法。

那么,为何要有这些不方便的限制?因为类通常声明在头文件中,而头文件往往被许多单 元所包含。但是,为了避免链接器设计的复杂化,C++要求每个对象都只能被定义一次。如果C++允许类内定义要作为对象被存在内存中的实体,那么这项要求 就无法满足了。关于C++设计时的一些折衷,参见《The Design and Evolution of C++》。

如果这个常量不需要被用于常量表达式,那么你的选择余地就比较大了:

	class Z {
static char* p; // initialize in definition
const int i; // initialize in constructor
public:
Z(int ii) :i(ii) { }
};

char* Z::p = "hello, there";
 
只有当static成员在类外被定义了,你才可以获取它的地址,例如:
	class AE {
// ...
public:
static const int c6 = 7;
static const int c7 = 31;
};

const int AE::c7; // definition

int f()
{
const int* p1 = &AE::c6; // error: c6 not an lvalue
const int* p2 = &AE::c7; // ok
// ...
}
原文地址:http://www.research.att.com/~bs/bs_faq2.html#in-class
评论
发表评论

您还没有登录,请登录后发表评论

shi5jin
搜索本博客
最近加入圈子
存档
最新评论