老师讲解
Q1:how 理解static?
A1 : 是类中的全局变量,被所有对象共享
1 通过对象访问得平均分
#include<iostream>
using namespace std;
class Student {
public :
//班级人数,静态数据成员
static int count;
//班级的总分数,静态数成员
static double total;
//定义带参数的构造函数
Student(double score) {
//this指针区分成员和非成员
this->score = score;
count++;
total += score;
}
double getAverage() {
return total / count;
}
double getTotal () {
return total;
}
private:
//个人分数
double score;
};
//static数据成员初始化
int Student::count = 0;
double Student::total = 0.0;
int main () {
/*
cout<<Student::count<<endl;
cout<<Student::total<<endl;
Student s1(70);
cout<<Student::count<<endl;
cout<<Student::total<<endl;
//另一种输出方法
cout<<s1.count<<endl;
*/
Student s1(70), s2(80);
//通过对象访问
cout<<s1.getAverage();
//通过类名访问
//cout<<Student::getAverage();
//cout<<Student::getTotal();
return 0;
}
执行结果:
2 通过类名访问得均分和总分
#include<iostream>
using namespace std;
class Student {
public :
//班级人数,静态数据成员
static int count;
//班级的总分数,静态数成员
static double total;
//定义带参数的构造函数
Student(double score) {
//this指针区分成员和非成员
this->score = score;
count++;
total += score;
}
static double getAverage() {
return total / count;
}
static double getTotal () {
return total;
}
private:
//个人分数
double score;
};
//static数据成员初始化
int Student::count = 0;
double Student::total = 0.0;
int main () {
/*
cout<<Student::count<<endl;
cout<<Student::total<<endl;
Student s1(70);
cout<<Student::count<<endl;
cout<<Student::total<<endl;
//另一种输出方法
cout<<s1.count<<endl;
*/
Student s1(70), s2(80);
//通过对象访问
//cout<<s1.getAverage();
//通过类名访问
cout<<Student::getAverage()<<endl;
cout<<Student::getTotal()<<endl;
return 0;
}
执行结果:
3 定义一个对象数组,继续执行上述操作
#include<iostream>
using namespace std;
class Student {
public :
//班级人数,静态数据成员
static int count;
//班级的总分数,静态数成员
static double total;
//定义带参数的构造函数
Student(double score) {
//this指针区分成员和非成员
this->score = score;
count++;
total += score;
}
static double getAverage() {
return total / count;
}
static double getTotal () {
return total;
}
private:
//个人分数
double score;
};
//static数据成员初始化
int Student::count = 0;
double Student::total = 0.0;
int main () {
/*
cout<<Student::count<<endl;
cout<<Student::total<<endl;
Student s1(70);
cout<<Student::count<<endl;
cout<<Student::total<<endl;
//另一种输出方法
cout<<s1.count<<endl;
*/
//定义对象数组
Student s[3] = {Student(70), Student(80), Student(90)};
//通过对象访问
//cout<<s1.getAverage();
//通过类名访问
cout<<Student::getAverage()<<endl;
cout<<Student::getTotal()<<endl;
//这两个语句等价
cout<<s[0].count<<endl;
cout<<Student::count<<endl;
return 0;
}
执行结果: