1. 只有当成员变量为static const 时,才可以在声明时直接定义,如下:
class X
{
public:
static const m_n = 100;
}
当然也可以将声明与定义分开,如下:
class X
{
public:
static const m_n;
}
// cpp文件
const int X::m_n = 100;
2.当成员变量为const时,只有在构造函数时,通过初始化列表初始化,如下:
class X
{
public:
X();
private:
const m;
const n;
}
//cpp
X::X(...):M(xx), n(oo)
{
}
3.当遇到在类内声明的常量,在类定义期间还需要使用,而此时该常量还未定义(赋值),比如,数组的长度,该如何解决?可使用枚举,如下:
// 错误 编译不过
class X
{
public:
X();
private:
const length = 10; // error 原因见条目2
char buf[length];
}
// 解决办法
class X
{
public:
X();
private:
enum {length = 10};
char buf[length];
}
利用枚举值可当做整型使用的特点
本文详细介绍了C++中成员变量的静态、常量特性及初始化策略,包括直接定义、构造函数初始化和使用枚举解决数组长度问题。
1426

被折叠的 条评论
为什么被折叠?



