静态成员函数
-
当需要获取总的人数时,还必须通过一个对象来访问,比如h1.getCount().
-
如果当前没有可用的对象时,就非常尴尬,不能访问getCount()!
-
如果为了访问总的人数,而特意去创建一个对象,就很不方便,
而且得到的总人数还不真实(包含了一个没有实际用处的人) -
解决方案:
把getCount()方法定义为类的静态方法!
类的静态方法:
- 可以直接通过类来访问【更常用】,也可以通过对象(实例)来访问。
- 在类的静态方法中,不能访问普通数据成员和普通成员函数(对象的数据成员和成员函数)
定义:
static int getCount();
实现:
方法实现的时候不需要加static
int Human::getCount() {
return humanCount;
}
调用:
//1. 通过类的域名直接调用
Human::getCount();
//2. 通过对象调用
Human h1;
h1.getCount();
Human.h
#pragma once
#include <string>
#include <iostream>
#include <Windows.h>
using namespace std;
class Human {
public:
Human();
string getName() const;
int getAge() const;
//定义了一个静态成员函数
static int getCount();
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(){
//静态成员函数中不能访问对象的数据成员和this指针
//cout << this->age << endl;
return humanCount;
}
main.cpp
#include "Human.h"
using namespace std;
void test(){
//直接使用类调用静态成员函数
cout << "总人数: " << Human::getCount() << endl;
}
int main(void) {
Human h1;
Human h2;
//使用对象调用静态成员函数
cout << "总人数: " << h1.getCount() << endl;
test();
system("pause");
return 0;
}
1)静态数据成员
- 对象的成员函数(没有static的成员函数)内部,可以直接访问“静态数据成员”
- 类的静态成员函数(有static的成员函数)内部,可以直接访问“静态数据成员”
- 即:所有的成员函数,都可以访问静态数据成员。
- 类不能直接访问普通的静态数据成员(Human::humanCount 非法)
2)静态成员函数
- 对象可以直接访问静态成员函数
- 类可以直接访问静态成员函数(Human::getHumanCount())
- 在类的静态成员函数(类的静态方法)内部,不能直接访问this指针和对象的数据成员!
- 在类的静态成员函数(类的静态方法)内部,只能访问类的数据成员