C++中static作用总结
1、隐藏功能(C/C++)
2、静态局部变量(C/C++)
3、类成员声明为static(C++)
隐藏功能
当全局变量和函数声明为static,只能在本文件中可见,对于其他文件不可见。其他文件可以有相同的函数/变量名字,不会冲突。
// test.cpp
#include <iostream>
using namespace std;
int n = 10;
int add(int a, int b) {
return a + b;
}
int main() {
cout << "10+20 = " << add(10,20) << endl;
cout << "n = " << n << endl;
return 0;
}
// add.cpp
#include <iostream>
int n = 12;
int add(int a, int b) {
return a + b + 1;
}
//编译出错
g++ -o test test.cpp add.cpp
/tmp/ccZ4vuaa.o:(.data+0x0): n 的多重定义
/tmp/ccR4As38.o:(.data+0x0):第一次在此定义
/tmp/ccZ4vuaa.o:在函数‘add(int, int)’中:
add.cpp:(.text+0x0): add(int, int) 的多重定义
/tmp/ccR4As38.o:test.cpp:(.text+0x0):第一次在此定义
collect2: 错误:ld 返回 1
在test.cpp中n和add加static,无错
静态局部变量
有两种变量存储在静态存储区:全局变量、static修饰的变量。静态存储区的变量在程序运行时会完成初始化(默认为0),也是唯一一次初始化。静态局部变量不会因为函数的结束而消失。它会在全局区直到程序的结束,但是作用域只有在该函数内。
#include <iostream>
using namespace std;
void func() {
static int a = 10;
a --;
cout << "a = " << a << endl;
}
int main() {
for (int i = 0; i < 10; i ++)
func();
return 0;
}
a = 9
a = 8
a = 7
a = 6
a = 5
a = 4
a = 3
a = 2
a = 1
a = 0
类成员修饰为static
1、静态成员变量
在类中的变量声明前加static,则为静态数据成员。
静态变量特点:
1)静态成员变量是所有该类的对象共有的,具有共享功能。
2)静态成员变量必须初始化,必须在类外初始化。其内存是在初始化的时候分配的。
2、静态成员函数
在类中的函数声明前加static,则为静态成员函数
静态函数的特点:
1)静态成员函数不能访问非静态成员变量和非静态成员函数。
2)非静态成员函数可以访问静态成员变量和静态成员函数。
#include <iostream>
using namespace std;
class Student {
private:
char* name;
float score;
static float total;
static int num;
public:
Student(char* name, float score) {
this->name = name;
this->score = score;
num ++;
total += score;
}
static float getAver() {
if (num == 0)
return 0;
return total / num;
}
};
float Student::total = 0.0;
int Student::num = 0;
int main() {
Student A("Tony", 80);
Student B("David",90);
cout << Student::getAver() << endl;
return 0;
}