class test{

public:
static int a;
void set(int i){a=i;}
};
int main(int argc, char* argv[])
{
 test::a = 2;
test x;
x.set(1);
return 0;
}编译时,test::a = 2;
x.set(1);
均抱错,怎么回事?static到底怎么用?

解决方案 »

  1.   

    static int a.
    a 則 屬於 類test ,但又獨立以類test. 怎麼說呢? 就是把this 指針隱藏了.所以上面的調用錯誤.
      

  2.   

    需要在test类的cpp文件的最上方(#include 之后),定义int test::a;然后才能编译通过。
      

  3.   

    class test{

    public:
    static int a;
    void set(int i){a=i;}
    };
    int test::a = 2;
    int main(int argc, char* argv[])
    {
    test x;
    x.set(1);
    return 0;
    }
      

  4.   

    需要在test类的cpp文件的最上方(#include 之后),定义int test::a;然后才能编译通过。
    楼上的朋友,为什么要这么做?
      

  5.   

    静态成员数据的定义说明和初始化要在类外进行.int test::a=0;