[C++]static

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jlran/article/details/52700117
#include <iostream>

using namespace std;
//关键字 static 可以用于说明一个类的成员,
//静态成员提供了一个同类对象的共享机制
//?把一个类的成员说明为 static 时,这个类无论有多少个对象被创建,这些对象共享这个 static 成员
//?静态成员局部于类,它不是对象成员
//
//静态成员函数数关键字static
//静态成员函数提供不依赖于类数据结构的共同操作,它没有this指针
//在类外调用静态成员函数用 “类名 :: ”作限定词,或通过对象调用


class Test{
private:
static int n; //声明与定义静态数据成员 公有静态数据成员
int a; //公有数据成员
public:
Test(){
a = 10;
}
void setN(int n, int a){ //成员函数访问静态数据成员
this->n = n;
this->a = a;
}
void getN(){
cout << "static int n: " << n << " int a: " << a<< endl;
}

};
int Test::n = 10; //声明与定义静态数据成员 初始值为10

int main()
{
Test t1;
Test t2;

t2.getN();
t1.getN();

t1.setN(20, 20);
t2.setN(30, 30);

t1.getN();
t2.getN();

getchar();
return 0;
}

猜你喜欢

转载自blog.csdn.net/jlran/article/details/52700117