C++类中静态成员和静态函数static
·
1. static本质
本质上,static是将变量的生命周期扩展到程序的整个生命周期。同时,局部变量存放的位置为程序的栈stack上,而静态变量存放的位置为程序的静态/全局数据区 (Static/Global Data Segment),注意,静态变量存放是全局数据区,不同于动态分配的变量,其分配是放堆(heap)上。
2. 对象的static成员变量和成员函数
用static定义了对象的成员变量后,该变量在类被定义的那一刻,该成员变量便产生了,更确切的是,程序启动的时刻,类被创建的时候,它不属于任何一个对象,而是被所有的对象所共享,注意,任意一个对象改变其值,其它的对象的该值也会发生改变。
用static定义成员函数,其功能只是允许通过类来调用成员函数,其实很多时候只是因为逻辑的问题,比如下面的代码,将平均函数定义为static函数,更符合逻辑。同时,需要注意的是,static成员函数不能直接访问或修改类的非静态数据成员。
#include <iostream>
using namespace std;
class Student {
public:
Student(int n, int a,float s) : num(n), age(a), score(s) {}
void display() const {
cout << "Number: " << num << ", Age: " << age << ", Score: " << score << endl;
}
//在函数前面加个static
void showAverageScore() {
if (count == 0) {
cout << "No students to calculate average score." << endl;
return;
}
cout << "Average Score: " << (sum / count) << endl;
}
void totalScore() {
sum += score;
count++;
}
private:
int num;
int age;
float score;
static float sum;
static int count;
};
float Student::sum = 0;
int Student::count = 0;
int main()
{
Student stud[3] = {
Student(1, 20, 85.5),
Student(2, 21, 90.0),
Student(3, 19, 78.5)
};
int n;
cout << "Enter number of students: ";
cin >> n;
for (int i = 0; i < n && i < 3; ++i) {
stud[i].display();
stud[i].totalScore();
}
cout << "Average Score: ";
//如果前面平均函数加了static,此处可以直接写为:
//Student::showAverageScore();
//逻辑上更合理一点,仅此而已
stud[0].showAverageScore();
std::cout << "Hello, World!" << std::endl;
return 0;
}
3. 总结
类的static,一般情况下,如果需要各个对象都共享一个变量的时候,就定义为static,而成员函数,则根据逻辑确定是否需要使用static,大多数情况下,可以没有必要定义一个static
更多推荐

所有评论(0)