静态数据成员
静态数据成员在内存中只占一份空间,而不是每个对象都为它分配空间,每个对象都可以引用这个数据成员。静态数据成员所占的空间不属于对象,同成员函数类似。它所占的内存在声明一个类的时候程序开始运行时就已被分配,并可被使用(同静态变量类似)。静态数据成员可以被初始化,但只能在体外被初始化。如果静态数据成员是公用的(在public下声明),则可以在体外采用类名或对象名直接引用,而如果它是私有的(在private下声明),则它只能采用对象名(不可能是对象名,因为对象的数据成员若是私有的,只能通过对象的成员函数引用)公用的成员函数引用
静态成员函数
它属于类,而不属于对象,没有this指针,因此它不能访问非静态数据成员(这里指的不能访问是指不能默认访问,要想访问某个对象的非静态数据成员时,只需加上对象名和成员运算符即可 ),实际上,静态成员函数是用来访问静态数据成员的。
class Box
{
public:
static int fun();
};
...
int main()
{
Box b1;
Box::fun(); // 正确,可以使用类名来访问静态成员函数
b1.fun(); //正确,也可以使用对象名来访问静态成员函数
return 0;
}
注意,可以使用对象名来访问静态成员函数,但这不代表该静态成员函数就属于这个对象,实际上它还是属于类的。
注意理解:采用非静态成员函数引用静态数据成员的方法、采用静态成员函数引用非静态数据成员的方法
理解时要始终抓住成员函数和数据成员到底是属于类的还是属于对象的,如果是属于类的,那么在引用时不需可以直接引用,如果是属于对象的,则在引用时要显式地指出对象名。
看一段代码😁
# 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; //普通成员函数也可以直接访问静态数据成员,因为后者是属于类的
count++; //同上
}
float Student::average()
{
return(sum/count); //静态成员函数访问静态数据成员
}
float Student::sum=0;
int Student::count=0;
int main()
{
Student std[3]=
{
Student(1001,18,70),
Student(1002,19,78),
Student(1003,20,98)
};
int n;
cout<<"input n"<<endl;
cin>>n;
for(int i=0; i<n; i++)
std[i].total();
cout<<"the average score of "<<n<<" is "<<Student::average()<<endl;
return 0;
}
运行结果:
input n
2
the average score of 2 is 74
Press any key to continue
再看一段:
# include<iostream>
using namespace std;
class Student
{
public:
Student(int n, int a, float s):num(n),age(a),score(s){}
void total();
float average(); 普通成员函数
private:
int num;
int age;
float score;
static float sum;
static int count;
};
void Student::total()
{
sum+=score;
count++;
}
float Student::average()
{
return(sum/count);
}
float Student::sum=0;
int Student::count=0;
int main()
{
Student std[3]=
{
Student(1001,18,70),
Student(1002,19,78),
Student(1003,20,98)
};
int n;
cout<<"input n"<<endl;
cin>>n;
for(int i=0; i<n; i++)
std[i].total();
cout<<"the average score of "<<n<<" is "<<std[0].average()<<endl;
return 0;
}
运行结果:
input n
2
the average score of 2 is 74
Press any key to continue
好好体会一下两者的区别:前者是用静态成员函数访问静态数据成员。后者是用非静态成员函数访问静态数据成员