C++基础知识 - 静态数据成员

“大众情人”, 静态数据成员

  • 需求分析:
    需要获取总的人数,如何实现?
    只能使用一个全局变量,然后在构造函数中对这个全局变量进行修改(加1)
    缺点:使用全局变量不方便,破坏程序的封装性。
  • 解决方案:
    使用类的静态成员。
  • 类的静态成员, 任何对象都可以访问和修改静态成员的值
    在这里插入图片描述
定义: 
static int humanCount;	

实现: 
在cpp文件中初始化静态成员变量
int Human::humanCount = 0;

Human::Human() {
	name = "无名";
	age = 18;	
	humanCount++;	//使用静态成员变量
}

调用:
Human h1, h2;
cout << "总人数: " << h1.getCount() << endl;	

 
Human.h

#pragma once
#include <string>
#include <iostream>
#include <Windows.h>
using namespace std;

class Human {
public:		
	Human();
	
	string getName() const;
	int getAge() const;
	int getCount() const;
private:		
	string name;	//姓名
	int age;		//年龄
	
	//定义了一个静态成员变量
	static int humanCount;	
};

 
Human.cpp

#include "Human.h"
#define		ADDR_LEN		64

//对静态成员变量进行初始化
int Human::humanCount = 0;

Human::Human() {
	name = "无名";
	age = 18;
	humanCount++;
}

string Human::getName() const {
	return name;
}

int Human::getAge() const {
	return age;
}

int Human::getCount() const {
	return humanCount;
}

 
main.cpp

#include "Human.h"

using namespace std;


int main(void) {
	Human h1;
	Human h2;

	cout << "总人数: " << h1.getCount() << endl;
	
	system("pause");
	return 0;
}

对于非const的类静态成员,只能在类的实现文件中初始化。

const类静态成员,可以在类内设置初始值,也可以在类的实现文件中设置初始值。(但是不要同时在这两个地方初始化,只能初始化1次)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值