关于静态变量

来源:互联网 发布:国防大学 知乎 编辑:程序博客网 时间:2024/04/29 16:01

对于函数来说,定义与声明很容易区别,但对于变量来说则不是,为了辨明,试验了一下几段代码:


#include <iostream>

using namespace std;
class test2{
public:
static int i;
int j;
void hehe(){cout<<i;}
};
//int test2::i;
int main(int argc, const char * argv[]) {
// test2 t2;
// t2.hehe();
return 0;
}
这段代码可以通过 ,此时主函数中未使用类test2;

#include <iostream>
using namespace std;
class test2{
public:
static int i;
int j;
void hehe(){cout<<i;}//!!!!!!
};
//int test2::i;
int main(int argc, const char * argv[]) {
test2 t2;
t2.hehe();
return 0;
}
这段则不行,如果将!!!!!!处改为cout<<j,则可以过,而且:

#include <iostream>
using namespace std;
class test2{
public:
static int i;
int j;
void hehe(){cout<<i;}
};
int test2::i;//!!!!!!
int main(int argc, const char * argv[]) {
test2 t2;
t2.hehe();
return 0;
}
这段代码又可以过,这说明类中的静态变量确实只是声明不会定义,必须在类外对其进行定义,而普通变量在类中会定义即开辟内存空间。

综上,原因应该是,在主函数中的变量使用前必须定义,而在类中则不必如此只要声明就好。这说明在类中static修饰的变量只是声明,而不加static修饰的变量则是定义,但在主函数中这二者都是定义。
0 0
原创粉丝点击