Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在函数中定义类的静态成员?_C++_Static Methods_Static Members - Fatal编程技术网

C++ 如何在函数中定义类的静态成员?

C++ 如何在函数中定义类的静态成员?,c++,static-methods,static-members,C++,Static Methods,Static Members,我有: 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

我有:

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};
^^^

注意到你缺少数组类型。

你可能需要花些时间在一本关于C++的好书上。您的
shared\u arr
成员缺少类型,
[]
是因为数组修饰符提供了不完整的类型,不能在类定义中使用。从更广泛的角度来看,几乎可以肯定,对于您试图解决的任何问题,都会有更好的解决方案。@KerrekSB:该成员是
静态成员。我相信您实际上可以在成员声明中使用不完整的类型。@KerrekSB对不起。戴维德罗·德里格斯·德里比亚斯:哦,很好,我没有想到这一点——有道理。我很困惑。函数内部的静态变量看起来就像外部的变量一样(范围区域除外)。@ymfoi:scope resolution操作符告诉编译器您正在初始化的数组是类成员。我的意思是函数内部的静态变量看起来很像全局变量。所以我想知道我是否可以在函数静态VARS中这样做。@ YMFOI:我刚才回答说,你不能。如果允许的话,考虑一下场景,如果函数被定义但从不调用会发生什么?当静态成员在其他地方使用时会发生什么情况,是否定义了它?它的状态是什么。。有没有更好的方法来满足我的需要?