【一天一篇CPP】静态成员

本文详细介绍了C++中静态数据成员和静态函数成员的概念及用法。通过实例演示了静态数据成员作为不同对象间的共享数据的特点,并展示了如何利用静态函数成员进行数据处理。此外,还探讨了静态成员在类中的作用及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.静态数据成员的作用:它是类的不同对象的共享数据,它是全局变量的替代品!!

一个例子:

#include <iostream>
using namespace std;
/*
//错误初始化
class Box{
public:
	Box(int h) : height(h){}
	static int height;
};*/
//正确初始化
class Box{
public:
	Box() {}
	Box(int h) { height = 5;}//这句话初始化无效!!!!
	static int height;
};

int Box::height = 10;//需要定义,不是声明!!!int 勿忘记,否则不能使用Box::height和a.height和b.height!!!

int main()
{
	Box::height++;
	cout <<  Box::height <<endl;
	Box a;
	a.height = 20;
	cout << Box::height <<endl;
	cout << a.height <<endl;

	Box b;
	b.height = 30;
	cout << Box::height <<endl;
	cout << a.height <<endl;
	cout << b.height <<endl;
	//Box::height和a.height和b.height是等价的

	cout << "size = " <<sizeof(Box) <<endl;	//size等于1
}

2.静态函数成员:没有this指针!不能直接使用非静态类成员,若要使用,则必须制定具体对象,而对静态成员,可以直接使用。

注意:

A对于静态函数成员,Box::volume()和box1.volume是等价的,这一点和静态数据成员一样!

B在静态函数成员中 ,由于没有this指针

cout << height <<endl;//合法
cout << width <<endl;//非法
cout << a.width <<endl;//合法

一个例子【静态数据成员+静态函数成员】

#include <iostream>

using namespace std;

class Student{
public:
	Student(int n,int a,float s) :num(n),
		age(a),score(s) {}
	void total();
	static float average();//静态函数
private:
	int num;
	int age;
	float score;
	static float sum;
	static int count;
};

void Student::total()
{
	sum += score;//score是自己的,sum是静态的
	count ++;	//count是静态的
}


float Student::average()//静态函数成员
{
	return (sum /count);
}

float Student::sum = 0;
int Student::count = 0;


int main()
{
	Student stud[3] = {
		Student(1001,18,70),
		Student(1002,19,78),
		Student(1005,20,98),
	};

	for(int i = 0; i < 3; i++)
		stud[i].total();

	cout << "average = " << Student::average() <<endl;

	return 0;
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值