笔记——C++全局静态变量的使用

在C++中使用全局静态变量时,定义必须包含在.h文件中并且要在一个类中。例如:

//glovbal.h

class global{
public:
    static int G_data;
    static string G_name;
};

仅仅如此并不能通过编译,因为并未给静态变量分配空间,需要在.cpp文件中进行实现。例如:

//global.cpp

int global::G_data = 0;
string global::G_name = "";

此时在其它类中进行引用时只需要包含global.h即可。例如:

//main.cpp
#include <iostring>
#include <stdio.h>
#include <stdlib.h>

#include "global.h"

using namespace std;
global::name = "hello world";

int main(int argc, char *argv[])
{
    cout << global::name;
    return 0;
}
发布了28 篇原创文章 · 获赞 4 · 访问量 7401

猜你喜欢

转载自blog.csdn.net/JuicyActiveGilbert/article/details/90047324