【自考】C++程序设计—静态对象static案例

本文通过四个案例详细介绍了C++中的静态对象static的使用,包括其在内存管理、作用域和生命周期等方面的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

案例1

案例2

案例3

案例4


案例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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值