目录
案例1
#include <iostream>
using namespace std;
class test{
private:
int n;
public:
test(int i){
n=i;
cout<<"构造:"<<i<<endl;
}
~test(){
cout<<"析构:"<<n<<endl;
}
int getn(){return n;}
void inc(){++n;}
};
void main()
{
cout<<"循环开始:"<<endl;
for(int i=0;i<3;i++)
{
static test a(3);
test b(3);
a.inc();
b.inc();
cout<<"a.n= "<<a.getn()<<endl;
cout<<"b.n= "<<b.getn()<<endl;
}
cout<<"循环结束"<<endl;
cout<<"退出主程序"<<endl;
}
案例2
#include <iostream>
using namespace std;
class TC{
private:
int A;
static int B;
public:
TC(int a){
A=a;B+=a;
//cout<<"B"<<B<<endl; B=6+2=8,B=8+4=12,因为B是静态成员所以最后显示B=12
}
static void display(TC c)
{
cout<<"A= "<<c.A<<" B= "<<B<<endl;
}
};
int TC::B=6;
void main()
{
TC a(2),b(4);
TC::display(a);
TC::display(b);
//第二个图显示结果
TC a(2);
TC::display(a);
TC b(4);
TC::display(b);
}
案例3
#include <iostream>
using namespace std;
class TC{
private:
int i,j;
public:
static int x;
TC(int a=0,int b=0,int c=0){
i=a;j=b;x=c;
}
void display()
{
cout<<"i= "<<i<<" j= "<<j<<"\t";
cout<<"x= "<<x<<"\n";
}
};
int TC::x=500;
void main()
{
cout<<"TC::x="<<TC::x<<endl;
TC a(20,40,10);
a.display();
TC b(30,50,100);
b.display();
//第二个结果
TC a(20,40,10),b(30,50,100);
a.display();
b.display();
cout<<"TC::x="<<TC::x<<endl;
}
案例4
//1404真题
class A
{
public:
A( );
void Show( );
~A();
private:
static int c;
};
int A::c=0;
A::A( )
{
cout<<"constructor."<<endl;
c +=10;
}
void A::Show( )
{
cout<<"c="<<c<<endl;
}
A::~A( )
{
cout<<"destrucator."<<endl;
}
int main( )
{
A a,b;
a.Show( );
b.Show( );
return 0;
}