You can define a static member of the class, be able to share data between multiple objects of the same kind.
The advantages of using a static member of the class are: ① name of the static member is in the scope of the class, thus avoiding name conflicts with other members of the class or global object; ② static members can implement the package, can be a private members, and the global must not. ③ static member is associated with a particular class, a clear structure.
classtest{
private:int x;int y;
public:
static int num;
static int Getnum(){
x+=5;
num+=15;return num;}};int test::num=10;int main(void){
test a;
cout<<test::num<<endl;//输出10
test::num=20;
cout<<test::num<<endl;//输出20
cout<<test::Getnum()<<endl;//输出35
cout<<a.Getnum()<<endl;//输出50return0;}
2. static member function
Member function can also be defined as static, plus static in front of the class function declaration became the general form of a static member function, declared as follows:
class 类名
{//类体
…
static 返回类型 函数名(类型1 参数名1,类型2 参数名2,…);
…
};
eg:
static int getcount(){return count;}//静态成员函数
Two ways of calling a static member function mode and static data members, static member function is part of a class, rather than part of the object. If you want to call public static member functions outside the class, can class scope operator (: :) and static member functions by calling the object name, for example:
cout<<Data::getcount()<<'\t'<<d.getcount();
The fundamental difference between static and non-static member functions member functions are: non-static member function pointers have this, but this is not a static member function pointers. Therefore, the static member functions of this class can not access non-static members. Static member function is specifically designed to access static data members.
Static member function can not be declared as const.
eg: compiler error, because the static member function can not reference non-static members. Static member function belongs to the class as a whole has been allocated a space before the class to instantiate an object, rather than a static member of the class must have memory space after the class to instantiate an object
eg: link error, because static data members of the class must be initialized before use. If we add before the main function int Point :: m = 0; then compile and link error, outputs an operation program.
classTest{
public:
Test(){
m++;//正确
}~Test(){
m--;//正确
}
static void output(){
cout<<m<<endl;}
private:
static int m;}int main(){
Test t;
t.output();return0;}