类和结构体外的Static

这里的static指的是在类外的static,意味着你要声明的是static的符号,链接将只在内部。(换句话说作用域只在他所在的.cpp文件)。

下面是几组例子来理解:

例子1:

main.cpp

#include <iostream>

using namespace std;

void fun(){
    cout << "fun() in main.cpp" << endl;
}

int main()
{
    fun();
    return 0;
}

static.cpp

#include<iostream>

using namespace std;

static void fun(){
    cout << "static fun() in static.cpp" << endl;
}

编译将不会报错,运行结果:

fun() in main.cpp

此时static.cpp中的fun()因为被static修饰,只在static.cpp中有效。

例子2:

main.cpp

#include <iostream>

using namespace std;

void fun(){
    cout << "fun() in main.cpp" << endl;
}

int main()
{
    fun();
    return 0;
}

static.cpp

#include<iostream>

using namespace std;

void fun(){
    cout << "static fun() in static.cpp" << endl;
}

编译后报错,无法运行,函数名重复了

例子3:

main.cpp

#include <iostream>

using namespace std;

int main()
{
    fun();
    return 0;
}

static.cpp

#include<iostream>

using namespace std;

static void fun(){
    cout << "static fun() in static.cpp" << endl;
}

编译后报错,无法运行,找不到fun()函数

例子4:

main.cpp

#include <iostream>

using namespace std;

extern void fun();

int main()
{
    fun();
    return 0;
}

static.cpp

#include<iostream>

using namespace std;

static void fun(){
    cout << "static fun() in static.cpp" << endl;
}

编译后报错,无法运行,找不到fun()函数(static.cpp中的fun()函数只在static.cpp生效,不能被main.cpp extern)

例子5:

main.cpp

#include <iostream>

using namespace std;

extern void fun();

int main()
{
    fun();
    return 0;
}

static.cpp

#include<iostream>

using namespace std;

void fun(){
    cout << "fun() in static.cpp" << endl;
}

编译不会报错,运行结果:

fun() in static.cpp

static.cpp的fun()没被static修饰,可以被extern,此时main.cpp中的fun()调用的是static.cpp中的fun()

最后修改:2023 年 04 月 28 日
如果觉得我的文章对你有用,请随意赞赏