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

要点:

1.静态成员变量必须在类的声明外进行初始化,一般在类的cpp文件初始化(在任何的大括号的外面);编译器不会自动对其初始化;

2.静态成员须用类名直接访问,不能有对象进行访问;

3.静态成员可以由静态函数访问,也可以由非静态函数访问;但是,静态函数只能访问静态成员,不能访问非静态成员。

欢迎大家批评指正...

http://blog.csdn.net/pbmichael/

 

#include  < iostream >
using   namespace  std;

class  sha{
    
static   int  a;               // static成员变量
     int  b;
public :
    
void   set ( int  i, int  j)       // 非static访问static成员变量
    {
      a
= i;
      b
= j;
    }
    
void  show();
};

int  sha::a = 0 ;                  // 在类的声明外,对static成员变量进行初始化     

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

int  main()
{
    sha x,y;
    x.
set ( 1 , 1 );
    x.show();                
// 此时输出1,1

    y.
set ( 2 , 2 );
    y.show();                
// 此时输出2,2

    x.show();                
// 此时输出2,1. 变量 a 的值发生了变化
                             
// 说明类sha的不同对象的static变量,共用同一内存!

    
return   0 ;
}

输出结果:

This is a static variable:         a=1
This is a non-static variable: b=1
This is a static variable:         a=2
This is a non-static variable: b=2
This is a static variable:         a=2
This is a non-static variable: b=1
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值