“大众情人”, 静态数据成员
- 需求分析:
需要获取总的人数,如何实现?
只能使用一个全局变量,然后在构造函数中对这个全局变量进行修改(加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次)