静态数据成员可以初始化,但只能在类体外进行初始化
如:
Int Box::height=10;
不能够使用参数初始化列表对静态数据成员进行初始化。
#include <iostream>
using namespace std;
class Box{
public:
Box(int,int);
int volume();
static int height;
int width;
int length;
};
Box::Box(int w , int len) { //静态数据成员height必须在类外进行初始化
width=w;
length=len;
}
int Box::volume() {
return(height*width*length);
}
int Box::height=10; //对对象的静态数据成员进行初始化,并且对象的静态数据成员初始化,必须在类的外部进行初始化
int main()
{
Box a(15,20),b(20,30);
cout<<a.height<<endl; //通过对象a引用静态数据成员
cout<<b.height<<endl; //通过对象b引用静态数据成员
cout<<Box::height<<endl; //通过类名引用静态数据成员,这个时候,要加上数据的作用域,即同一类型的作用域
cout<<a.volume()<<endl; //调用volume函数,计算体积,输出结果。
return 0;
}
静态成员函数
**#include <iostream>
using namespace std;
class Student{
public:
Student(int n,int a,int 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 stud[3]={
Student(1001,18,70),
Student(1002,19,78),
Student(1005,20,98)
};
int n;
cout<<"please input the number of students:";
cin>>n;
for(int i=0;i<n;i++)
{
stud[i].total();
}
cout<<"The average score of"<<n<<"student is"<<Student::average()<<endl;
return 0;
}
**
/home/andrew/文档/Clion/untitled5/cmake-build-debug/untitled5
please input the number of students:3
The average score of3student is82
Process finished with exit code 0