关于静态成员变量和静态成员函数的一点心得(续)

上次的code可以做如下改动:

 

#include  < iostream >
using   namespace  std;

class  sha
{
        
static   int  a;
        
int  b;
public :
        
void   set ( int  i, int  j)
        {
                
// a=i;
                b = j;
        }
        
static   void  seta( int  i)
        {
                a 
=  i;
        }
        
void  show();
        
static   void  showa();
};

void  sha::show()
{
        
// cout<<"this is static a="<<a<<endl;
        std::cout << " this is non-static b= " << b << endl;
}

void  sha::showa()
{
        
// cout<<"this is static a="<<a<<endl;
        std::cout << " this is static a= " << a << endl;
}

int  sha::a  =   1 ;

int  main()
{
        sha x,y;
        x.
set ( 1 , 1 );
        x.show();

        y.
set ( 2 , 2 );
        y.show();

        y.seta(
10 );
        x.show();
        x.showa();

        
return   0 ;
}

输出结果:

this is non-static b=1
this is non-static b=2
this is non-static b=1
this is static a=10 

静态成员须用类名直接访问,不能有对象进行访问, 看如下例子:

 

#include < iostream >  
#pragma  warning(disable: 4101) 
using   namespace  std;

class  C0 

public :
static   void  print0() // 这里用static 

cout
<< " C0 print0 " << endl; 


public
class  C1 


/// //
/// //
public
void  print1() 

cout
<< " C0 C1 print1 " << endl; 

/* ***found**** */  
static   void  print2()    // 这里用static 

cout
<< " C0 C1 print2 " << endl; 

}; 
}; 

int  main() 

    C0::print0();
/// //

    C0::C1 obj2; 
    obj2.print1(); 
/// /

    C0 obj;           
// 这两行也可以改为:
    obj.C1::print2();  // C0::C1::print2();
/*
***found**** */  

    
return   0 ;
}

输出结果:

 

C0 print0
C0 C1 print1
C0 C1 print2

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值