如果一个变量是类的一部分,但却不是类的各个对象的一部分,则称它为static静态成员。
一个static成员只有唯一的一份副本,而不像非static成员那样在每个对象里各有一份副本。与此类似,一个需要访问类成员,不需要指定特定对象去调用的函数,也被称为static成员函数。
静态成员(包括函数和数据成员)在类里面声明后,都必须在某个地方另行定义。见如下实例:
#include <iostream>
using namespace std;
class hello
{
private:
int times;
static hello default_t; //无法直接初始化
public:
hello(int _t = default_t.times):times(_t){};
static void set_default(int);
void print();
};
void hello::print()
{
for(int i=0;i!=times;i++)
cout<<"hello"<<endl;
}
void hello::set_default(int _t) //另行定义,不用再写static
{
default_t.times = _t;
}
hello hello::default_t(4); //另行定义
int main(int argc, char* argv[])
{
//hello::set_default(5);
//hello hello_world(2);
hello hello_world;
hello_world.print();
return 0;
}
在类里声明静态整形常量
#include <iostream>
using namespace std;
class hello
{
private:
int times;
static const int default_t = 5;
public:
hello(int _t = default_t):times(_t){};
void print();
};
void hello::print()
{
for(int i=0;i!=times;i++)
cout<<"hello"<<endl;
}
int main(int argc, char* argv[])
{
//hello hello_world(2);
hello hello_world;
hello_world.print();
return 0;
}
静态内置类型与例1相似
#include <iostream>
using namespace std;
class hello
{
private:
int times;
static int default_t ;
public:
hello(int _t = default_t):times(_t){};
static void set_default(int);
void print();
};
void hello::print()
{
for(int i=0;i!=times;i++)
cout<<"hello"<<endl;
}
void hello::set_default(int _t)
{
hello::default_t = _t;
}
int hello::default_t = 3;
int main(int argc, char* argv[])
{
//hello hello_world(2);
//hello::set_default(10);
hello hello_world;
hello_world.print();
return 0;
}