c++l类中static成员函数和成员数据变量使用

c++中为了保护类的封装性,提出了static成员来代替全局变量,下面我们来了解一下static成员的使用方法:程序通过vs2008调试成功

例一:

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cassert>
#include<malloc.h>
#include<fstream>
class test
{
public:
      static void show(void);//static成员函数只能访问static数据成员,不能访问普通的数据成员
private:
   static int a;//static数据成员可以类内所有成员函数访问
   int b;

};
int test::a = 15;//类static数据成员必须在类声明处外初始化
void test::show (void){std::cout<<test::a<<std::endl;}//类static成员函数必须在类外面定义,在类结构内只能声明
int main(void )
{
    test test_1;
    test_1.show();//访问类static成员和普通成员一样,但是要注意static成员不能用this指针访问
    system("pause");
    return 0;
}

例二:记录有多少个test对象被创建

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cassert>
#include<malloc.h>
#include<fstream>
class test
{
public:
    test(){a=a+1;}
    ~test(){}
      static void show(void);
private:
   static int a;
   int b;

};
//void test::initial(int& lhs){test::a = lhs;}
int test::a = 0;
void test::show (void){std::cout<<test::a<<std::endl;}
int main(void )
{
    test test_1;//创建一个对象
    test_1.show();//输出a=1
    test test_2;//创建第二个对象
    test_2.show();//输出a=2   

    system("pause");
    return 0;
}


 


 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值