C++静态数据成员实现

静态数据成员是在一个类中用关键字static声明的数据成员。在C++中,一般使用静态成员来代替C语言的全局变量,以达到数据共享。C和C++的全局变量有一定的局限性,可以任意被修改,也容易和其它的变量名冲突,故在C++中,一般不使用全局变量。

静态数据成员必须进行初始化,初始化应在类体外进行,静态数据成员也可以引用,但不能引用私有数据部分。

接下来看一个例子:

#include <iostream>
#include <cstring>
using namespace std ; 
class Student 
{
	private :
		//静态成员变量 
		static int age ;
		static float score ; 
		string name ;
	public :
		static int x , y ;
		//构造函数 
		Student();
		//析构函数 
		~Student(); 
		//设置信息 
		int setstuinfo(int age , float score , string name);
		//打印信息 
		int Printstuinfo();
};

//静态成员必须初始化 
int Student::age = 24 ; 
float Student::score = 86.6 ; 
int Student::x = 100 ; 
int Student::y = 200 ;

Student::Student()
{
	this->name = "YYX" ;
	cout << this->name << endl ;
	cout << this->age << endl ; 
	cout << this->score << endl ; 
}
Student::~Student()
{
	this->name = "NULL";
	cout << this->name << endl ;
}
int Student::setstuinfo(int age , float score , string name)
{
	this->age = age ; 
	this->score = score ; 
	this->name = name ;
}

int Student::Printstuinfo()
{
	cout << this->name << endl ;
	cout << this->age << endl ; 
	cout << this->score << endl ; 
}

int main(void)
{
	Student stu1 ;
	//指针 
	Student *p ;
	p = &stu1 ;
	p->setstuinfo(25,96,"XXX");
	p->Printstuinfo();
	//静态成员的引用---->不可以引用私有成员
	cout << p->x << endl ; 
	cout << p->y << endl ;
	Student::x = 80 ;
	Student::y = 90 ;
	cout << p->x << endl ; 
	cout << p->y << endl ;
	return 0 ;
}
运行结果:

YYX

24 

86.6

XXX

25

96

100

200

80

90

NULL


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Engineer-Bruce_Yang

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值