使用静态数据成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;
class test
{
int k;
public:
static int n;//静态数据成员
test(int kk)
{k=kk;n++;}//类内直接引用静态数据成员
void disp()
{cout<<"n="<<n<<"k="<<k<<endl;}
};
int test::n=0;//类外对静态数据成员初始化
void main()
{
test t1(10);
t1.disp();//n=1,k=10
test t2(20);
t2.disp();//n=2,k=20
test::n++;
t2.disp();//n=3,k=20
}