static有两种用法:
- 静态变量:函数中的变量,类中的变量。
- 静态类中的成员:类对象和类中的函数。
接下来就这两种用法,我来进行深入的阐述。
1,静态变量。
(1)函数中的静态变量。
static在程序周期中只会分配一次,而且按值传递。通过以下的例子来进行说明:
#include<iostream>
using namespace std;
void fun1()
{
static int m = 1;
cout<<m<<endl;
m++;
}
int main()
{
for(int i=0;i<4;i++)
{
fun1();
}
return 0;
}
输出为1,2,3,4;
因为static在程序周期中只会赋值一次,即初始值为1,后续都是以1为基准进行运行的,不会因为函数的每次使用而重新赋值。这在需要一个初始值的C/C++程序是非常重要的,因为它是按值传递的。
(2)类中的静态变量
因为声明的static只会被初始化一次,因为它们在各自的静态存储中分配了空间,即同名的static在使用时会被共用。因此不能出现在类的默认构造函数中,不允许出现一个static的多个副本,因为它在对象的创建过程中会被初始化很多次,因此这样是不被允许的。但是可以在类中初始化它。例如下面的代码:
class Demo
{
public :
static int var;
Demo();
~Demo();
};
类中的静态成员变量初始化可以在类中初始化或者在范围解析符中初始化。例如:
class Demo
{
public :
static int var;
Demo();
~Demo();
};
int Demo::var = 1;
int main()
{
Demo demo;
cout<<demo.var;
return 0; //输出为1
2.静态对象
对象可以有静态的或者非静态的,这两种函数的区别,我会利用下面的代码进行说明:
#include<iostream>
using namespace std;
class Demo
{
public:
Demo() { cout << "The Demo has been created;"<<endl; };
~Demo() { cout << "The Demo has been deleted"<<endl; };
};
int main()
{
int num = 1;
if (num == 1)
{
Demo demo;
}
cout << "The program is over"<<endl;
return 0;
}
The Demo has been created;
The Demo has been deleted
The program is over
结果输出为这样,表示Demo的创建删除的周期只在if中,这是没有使用static的情况,接下来看看使用了static的情况:
#include<iostream>
using namespace std;
class Demo
{
public:
Demo() { cout << "The Demo has been created;"<<endl; };
~Demo() { cout << "The Demo has been deleted"<<endl; };
};
int main()
{
int num = 1;
if (num == 1)
{
static Demo demo;
}
cout << "The program is over"<<endl;
return 0;
}
The Demo has been created;
The program is over
The Demo has been deleted
结果输出为这样,表示Demo在整个函数周期中,当程序结束时才会析构,这便是static在类中的使用。
- 类中的静态函数。
就像类中的静态数据成员或静态变量一样,静态成员函数也不依赖于类的对象。我们被允许使用对象和’.'来调用静态成员函数。但建议使用类名和范围解析运算符调用静态成员。
允许静态成员函数仅访问静态数据成员或其他静态成员函数,它们无法访问类的非静态数据成员或成员函数。
这些便是我对static的一些认识,若有错误请大家指正。