C++之类的静态数据成员

什么是类的静态数据成员?

静态数据成员也也是一个类的数据成员。但是这个数据成员不根据所定于的对象而存在。而是一个属于类的数据成员。
具体实现
定义:static int a;
实现:int Human::a=10; //不需要加static

类的静态成员函数有什么用?

举个例子,例如有一个人的类,一个对象为一个人。要求实现算出已经定义了多少个人时就可以使用类的静态成员函数。

#include<iostream>
#include<Windows.h>

using namespace std;

//定义一个类
class Human {
private:
	int a;
	int b;
	static int c;
public:
	Human();	//手动定义默认构造函数
	Human(int a);	//自定义重载构造函数
	Human(const Human &other);	//声明拷贝构造函数
	Human& operator=(const Human &other);//赋值构造函数的声明
	void test();
};
int Human::c = 0;
Human::Human() {		//手动定义默认构造函数实现
	a = 10;  
	b = 4;
	c++;
}
Human::Human(int a) {//自定义重载构造函数的实现
	this->a = a;
	c++;
}
Human::Human(const Human &other) {	//拷贝构造函数的实现
	this->a = other.a;
	this->b = other.b;
	c++;
}
Human& Human::operator=(const Human &other) {	//赋值构造函数的实现
	this->a = other.a;
	this->b = other.b;
	return *this;
}
void Human::test() {
	cout << this->c << endl;
}
int main() {
	Human zhangsan(3);	//定义了一个张三类,同时通过构造函数对类数据成员初始化
	Human lisi = zhangsan;//通过拷贝构造函数,把参数赋值给lisi对象
	Human wanger(6);	//定义王二对象
	wanger = zhangsan;	//调用赋值构造函数
	wanger.test();
	system("pause");
	return 0;
}

结果:3

使用静态数据成员注意:

1、在无const定义数据成员时,不能初始化,只能到实现时初始化。
2、在有const定义数据成员时,可以初始化,但是前后初始化只能一次。
3、在实现地方初始化不需要加static
4、类中普通成员函数对类的静态数据成员可用可修改。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小生乔克

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值