有时候,一个类的所有对象都共享相同的数据,这样节约存储,不需要在每个类实例化后都放相同的数据。那么有哪些方法来实现呢?
1 使用static const, static表示只为一个编译单元。
class A
{
public:
static const int SIZE1 = 10; //VC不支持
static const int SIZE2 = 5;
private:
int array1[SIZE1];
int array2[SIZE2];
};
class A
{
public:
static const int SIZE1;
static const int SIZE2;
private:
int array1[SIZE1];
int array2[SIZE2];
};然后在类外定义const int A::SIZE1 = 10;const int A::SIZE2 = 5;
2 使用枚举,不占用对象存储空间,缺点是只能表示整形。
class A
{
public:
enum
{
SIZE1 = 100,
SIZE2 = 200
};
private:
int array1[SIZE1];
int array2[SIZE2];
};
3 直接独立出一个文件里面放const int max = 1024; 直接include该文件即可