c++ 的static关键字修饰c++中类的成员函数

1,静态成员函数的意义,不在于信息共享,数据沟通,而在于管理静态数据成员, 完
成对静态数据成员的封装。
2,静态成员函数只能访问静态数据成员。原因:非静态成员函数,在调用时this 指
针被当作参数传进。而静态成员函数属于类,而不属于对象,没有 this 指针。

 

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>

using namespace std;


class Student
{
public:
	Student(int num, double score) {
		m_num = num;
		m_score = score;

		count++;
		sum_score += score;
	}

	static double getAvg()
	{
		return sum_score / count;
	}

private:
	int m_num; //学号
	double m_score; //成绩

	//定义一个记录学生个数的静态变量
	static int count; //记录目前Student类已经创建了多少个学生对象。
	static double sum_score;// 所有已经定义学生对象的总score和。
};

//初始化静态成员变量
int Student::count = 0;
double Student::sum_score = 0.0;

int main(void)
{
	Student s1(1, 80);
	Student s2(2, 90);
	Student s3(3, 80);

	//Student::sum_score / Student::count;
	//使用一个静态的成员函数
	double avg = Student::getAvg(); //可以给他当成一个 类的全局函数

	//s1.getAvg();

	cout << "目前的学生的平均分数是" << avg << endl;
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值