于静态成员变量的二种访问权限的使用区别
2016-06-03 17:26
183 查看
关于静态成员变量的二种访问权限的使用区别,一种是公有,一种是私有,访问的区别,见代码:
/*
我们需要了解的是,假如我们要在一个类中的所有对象间共享某种数据,
不如将该数据声明为静态成员变量。假如你不想让该类外的所有函数都
可以访问该数据,那么不妨将某定义为私有成员,那么就只有该类的公
有成员方法才可以访问它。当然访问的前提是必须创建一个属于该类的
对象。
*/
#include<iostream>
using namespace std;
class A
{
public:
A(int x):it(x){total++;}
static int total; //公有静态变量
void func(){cout<<A::sum<<endl;}
~A(){total--;}
int getIt(){return it;}
void set(int age){it = age; }
private:
int it;
static int sum;
};
int A::total = 0;
int A::sum = 100;
void show1()
{
cout<<A::total<<endl;
}
//下面是错误的,外部不能访问私有成员,即使是静态变量
/*
void show2()
{
cout<<A::sum<<endl;
}
*/
int main()
{
/* const int max = 5;
int i;
A *a[max];
for(i=0;i<max;i++)
{
a[i] = new A(i);
}
for(i=0;i<max;i++)
{
cout<<"该类有: "<<A::total<<" 个对象。"<<endl;
cout<<"正在删除第: "<<a[i]->getIt() <<" 个对象。"<<endl;
delete a[i];
}
*/
//下句说明,静态变量在没有对象是就存在。
A a(2);
a.func() ;
show1();
//shwo2();
system("pause") ;
}
/*
我们需要了解的是,假如我们要在一个类中的所有对象间共享某种数据,
不如将该数据声明为静态成员变量。假如你不想让该类外的所有函数都
可以访问该数据,那么不妨将某定义为私有成员,那么就只有该类的公
有成员方法才可以访问它。当然访问的前提是必须创建一个属于该类的
对象。
*/
#include<iostream>
using namespace std;
class A
{
public:
A(int x):it(x){total++;}
static int total; //公有静态变量
void func(){cout<<A::sum<<endl;}
~A(){total--;}
int getIt(){return it;}
void set(int age){it = age; }
private:
int it;
static int sum;
};
int A::total = 0;
int A::sum = 100;
void show1()
{
cout<<A::total<<endl;
}
//下面是错误的,外部不能访问私有成员,即使是静态变量
/*
void show2()
{
cout<<A::sum<<endl;
}
*/
int main()
{
/* const int max = 5;
int i;
A *a[max];
for(i=0;i<max;i++)
{
a[i] = new A(i);
}
for(i=0;i<max;i++)
{
cout<<"该类有: "<<A::total<<" 个对象。"<<endl;
cout<<"正在删除第: "<<a[i]->getIt() <<" 个对象。"<<endl;
delete a[i];
}
*/
//下句说明,静态变量在没有对象是就存在。
A a(2);
a.func() ;
show1();
//shwo2();
system("pause") ;
}
相关文章推荐
- UVa11462
- OC与swift相互调用
- jQuery select 清空保留第一项
- menu
- vue实例属性(vm.$els)
- jquery file upload 后台收到的文件名中文乱码, filename中文乱码
- 浅谈自动化测试
- 加个标记达到同步效果~
- 最小公倍数的计算
- db2 导入导出命令操作步骤
- iOS 传值方法(属性传值、代理传值、Block、通知、单例)
- A java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Ecl
- 微信支付调起支付控件一闪而过
- servlet单实例多线程运行原理
- 反射获取对象中属性的信息,包括属性的特性
- window上使用you-get下载视频(一)
- 单例模式
- 使用html5中video自定义播放器必备知识点总结以及JS全屏API介绍
- 第十五周项目1:阅读程序,领会STL用法(4)
- 【Android】Android之命令行安装apk