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

静态成员函数

  • 当需要获取总的人数时,还必须通过一个对象来访问,比如h1.getCount().

  • 如果当前没有可用的对象时,就非常尴尬,不能访问getCount()!

  • 如果为了访问总的人数,而特意去创建一个对象,就很不方便,
    而且得到的总人数还不真实(包含了一个没有实际用处的人)

  • 解决方案:
    把getCount()方法定义为类的静态方法!

类的静态方法:

  1. 可以直接通过类来访问【更常用】,也可以通过对象(实例)来访问。
  2. 在类的静态方法中,不能访问普通数据成员和普通成员函数(对象的数据成员和成员函数)
定义: 
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指针和对象的数据成员!
  • 在类的静态成员函数(类的静态方法)内部,只能访问类的数据成员
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值