有四个文件:class.h,class.cpp,fun.h,fun.cpp
1.第一种情况
class.h
#include<stdio.h>
class C
{
public:
static int i = 0;
};
class.cpp
#include "class.h"
int main()
{
C c;
return 0;
}
class.h:5: error: ISO C++ forbids in-class initialization of non-const static member `i'
2.第二种情况
class.h
#include<stdio.h>
class C
{
public:
static int i;
};
int C::i(1);或者 int C::i = 1;
class.cpp
#include "class.h"
#include "fun.h"
int main()
{
C c;
return 0;
}
fun.h
int fun();
fun.cpp
#include "class.h"
int fun()
{
C c;
return 0;
}
multiple definition of `C::i
3.第三种情况
class.h
#include<stdio.h>
class C
{
public:
static int i;
};
class.cpp
#include "class.h"
#include "fun.h"
int C::i = 0;
int main()
{
C c;
printf("%d\n",c.i);
fun();
printf("%d\n",c.i);
return 0;
}
fun.h
int fun();
fun.cpp
#include "class.h"
int C::i = 1;
int fun()
{
C c;
printf("%d\n",c.i);
return 0;
}
multiple definition of `C::i'
4.第四种情况
class.h
#include<stdio.h>
class C
{
public:
static int i;
};
class.cpp
#include "class.h"
#include "fun.h"
int C::i = 0;
int main()
{
C c;
printf("%d\n",c.i);
fun();
printf("%d\n",c.i);
return 0;
}
fun.h
int fun();
fun.cpp
#include "class.h"
int fun()
{
C c;
c.i = 1;
printf("%d\n",c.i);
return 0;
}
输出:
0
1
1