如何在函数中定义一个类的静态成员?
这里我有:如何在函数中定义一个类的静态成员?
class X {
public:
static int shared_arr[];
static void alloc_and_init() {
// Since any static variables defined in the function are allocated some space.
// So can I define X::shared_arr here (using the space the static variable for X::shared_arr)?
// I think it would be a convenient way to make an approach of some basic memory allocation and initialization.
}
};
没有,你将有只有一个CPP文件&任何功能之外来定义它。
int X::shared_arr[MAX_SIZE] = {0};
^^^
请注意,您缺少数组类型。
我很困惑。函数内部的静态变量看起来就像外部的变量(范围区域除外)。 – Determinant 2012-03-19 14:22:44
@ymfoi:范围解析运算符告诉编译器你正在初始化的数组是一个类成员。 – 2012-03-19 14:26:47
对不起......我只是忘了。 – Determinant 2012-03-19 14:27:18
你应该花一些时间在C++上写一本好书。您的'shared_arr'成员缺少类型,'[]'是数组修饰符给出的不完整类型,不能在类定义中使用。从更广泛的角度来看,几乎可以保证针对您要解决的任何问题提供更好的解决方案。 – 2012-03-19 14:22:01
@KerrekSB:该成员是一个“静态”成员。我相信你实际上可以在成员的*声明中使用不完整的类型。 – 2012-03-19 14:24:37
@KerrekSB对不起。我忘了输入。 – Determinant 2012-03-19 14:25:18