C++类中使用静态成员变量

如果需要在类中使用静态成员变量,需要在头文件和.cpp文件各定义一次

例如,有StaticTest.h和StaticTest.cpp两个文件

StaticTest.h:

class StaticTest
{
private:
    static int value;

public:
    static void print();
};

 

StaticTest.cpp

#include "StaticTest.h"

#include <iostream>
using namespace std;

int StaticTest::value; //必须要在.cpp文件再定义一次

void StaticTest::print()
{
    cout << value;
}

 

============================================================================

而如果使用的是全局静态变量(非类成员),则不需要在.cpp文件再定义一次

例如,StaticTest.h:

static int global_value;

class StaticTest
{
public:
    static void print();
};

 

StaticTest.cpp

#include "StaticTest.h"

#include <iostream>
using namespace std;

void StaticTest::print()
{
    cout << global_value; //直接使用
}

 

posted @ 2022-11-11 13:56  Clotho_Lee  阅读(87)  评论(0)    收藏  举报