现在的位置: 首页 > 综合 > 正文

面向对象的程序设计学习笔记-17-静态成员数据

2014年02月17日 ⁄ 综合 ⁄ 共 1451字 ⁄ 字号 评论关闭

/*
静态成员包含静态数据成员和静态成员函数
一旦指定为static,不管该类创建多少个对象,静态数据成员都只有一个静态数据值。
因此,静态数据成员是该类所有对象共享的成员,也是连接该类中不同对象的桥梁
*/
#include<iostream>
using namespace std;
class counter
{
public:
static long count_l;//公有静态数据成员
counter(char c);//构造函数,令数据成员count自增
counter();//无参数的构造函数
static int home();//静态成员函数,读静态数据成员count的值
int read_ch_int();
char read_ch();
long get_count_l();//读取count_l数据成员
~counter();//析构函数
private:
static int count;//私有静态数据成员
char ch;
};
counter::counter(char c)//每调用一次构造函数,count则自加1。所以静态数据成员常用以记录某个类所创建的对象个数
{
count++;ch=c;
}
counter::counter()
{
count_l++;
}
int counter::home()//该函数为静态成员函数。读取count的值
{
return count;
}
int counter::read_ch_int()//请注意,此处的ch类型与函数的返回类型是不一样的
{
return ch;//返回的是字符型所对应的ASII码。比如a,ch=a则返回的是97
}
char counter::read_ch()//当返回的函数值与ch的类型一致时,c1(1)中的“1”是一ASII码进行显示的
{
return ch;//返回的是字符型所对应的ASII码。比如a,ch=a则返回的是97
}
long counter::get_count_l()
{
return count_l;
}
counter::~counter()
{
count--;ch=0;//析构函数,令count值减1,同时使得ch值为0
count_l--;
}

int counter::count=100;//静态数据成员的初始化
long counter::count_l=5;//静态公有数据成员的初始化

void main()
{
counter c0('a'),c1(1),c2(2),c3(3),c4(4);
cout<<"counter当前的值:"<<counter::home()<<endl;//对于静态函数的操作,因为它不属于某个对象,它是属于类的
cout<<"对象0:"<<c0.read_ch()<<endl;
cout<<"对象1:"<<c1.read_ch()<<endl;
cout<<"对象2:"<<c2.read_ch()<<endl;
cout<<"对象3:"<<c3.read_ch()<<endl;
cout<<"对象4:"<<c4.read_ch()<<endl;
cout<<"请注意输出结果的对比:\n";
cout<<"对象0:"<<c0.read_ch_int()<<endl;
cout<<"对象1:"<<c1.read_ch_int()<<endl;
cout<<"对象2:"<<c2.read_ch_int()<<endl;
cout<<"对象3:"<<c3.read_ch_int()<<endl;
cout<<"对象4:"<<c4.read_ch_int()<<endl;
}

抱歉!评论已关闭.