函数前加static,这要分几种情况说明。
1.在类成员函数前加static,此成员函数就成为静态函数,不依赖对象存在。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <set> using namespace std; class Test{ public: Test(){ } ~Test(){ } static void fun(){ cout<<"静态成员函数"<<endl; } }; int main() { Test::fun(); } |
fun()像普通函数一样,直接调用,并不一定需要有对象。
更多static可以转到:static作用? ?? ??类中成员前加static
2.在C语言里面,还有一种就是直接在函数前加static,这样作用就是此函数只能在此文件内可用,不能用于其它文件内。
只是限制在当前源文件—只是对于编译期间的限制。
但实际上,运行时,static和普通的extern 的函数/变量,没有区别。