1、auto关键字
默认省略,在栈内分配空间,分为局部变量和全局变量
2、extern关键字,跨文件
声明全局变量或函数,该变量已在其他文件中定义为全局变量(auto),若要使用的变量是static类型,则报错‘未定义变量’
3、register关键字
定义寄存器变量,C中取地址运算符&不能作用此类变量,C++可以但有局限性,好处:提高读取速度 link
4、static关键字,作用域:被声明的文件
局部静态变量,编译阶段在静态区分配空间,生命周期是整个程序执行期间
面向对象中的使用:
修饰成员变量,在类外通过类名或对象名初始化(type base::var=key;),被所有对象共享(包括派生类对象),也可以独立访问
修饰成员函数,为所有对象共享,不含this指针,只能访问类中static成员;可以独立访问(不创建对象时可访问 base::fun();)
隐藏作用:在一个项目内,未加static前缀的成员都具有全局可见性,其他源文件可以访问。利用static的文件作用域的特性可以在不同文件中定义同名成员,不必担心命名冲突。
注意:不可以用const和static同时修饰成员函数
①、统计
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 #define MAX 10 5 using namespace std; 6 7 //已知3名学生的学号、姓名和某门课程成绩,使用面向对象的方法计算他们的平均分 8 class Student 9 { 10 private: 11 int id; 12 char name[MAX]; 13 float score; 14 public: 15 Student(){} 16 Student(const int Id,const char* nm,const float sc){ 17 strcpy(this->name,nm); 18 this->id = Id; 19 this->score = sc; 20 } 21 void addScores(){ 22 total_students++; 23 total_score += score; 24 } 25 26 static float total_score; 27 static int total_students; 28 static string schoolName; 29 30 static float get_aver(){ 31 return total_score/total_students; 32 } 33 }; 34 35 string Student::schoolName="CMU"; 36 float Student::total_score=0; 37 int Student::total_students=0; 38 39 int main() 40 { 41 Student stu[3]={ 42 Student(1001,"zhang",80), 43 Student(1002,"liu",88), 44 Student(1003,"wang",82) 45 }; 46 for(int i=0; i<3; i++) 47 stu[i].addScores(); 48 cout<<"school = "<<Student::schoolName<<endl; 49 cout<<"average = "<<Student::get_aver()<<endl; 50 }