在 C++ 中使用头文件时如何以及在何处定义类变量

Moo*_*lit 1 c++ header class-variables

/*
 * CDummy.h
 */
#ifndef CDUMMY_H_
#define CDUMMY_H_

class CDummy {

public:
    CDummy();
    virtual ~CDummy();
};

#endif /* CDUMMY_H_ */
Run Code Online (Sandbox Code Playgroud)

我读过不应在头文件中声明类变量。这是对的吗?所以我在下面的cpp文件中声明它:

/*
 * CDummy.cpp
*/

#include "CDummy.h"

static int counter = 0; //so here is my static counter. is this now private or public? how can i make it public, i cannot introduce a public block here.

CDummy::CDummy() {
  counter++;

}

CDummy::~CDummy() {
    counter--;
}
Run Code Online (Sandbox Code Playgroud)

使用此代码我无法从我的主程序访问类变量....

谢谢

jua*_*nza 5

“类变量”需要属于一个类。所以它必须在类定义中声明。如果类定义在头文件中,那么类变量声明也必须在头文件中。

类变量的定义应该放在一个实现文件中,通常是定义类成员的文件。这是一个简化的示例:

foo.h

struct Foo
{
  void foo() const;
  static int FOO;   // declaration
};
Run Code Online (Sandbox Code Playgroud)

文件

void Foo::foo() {}
int Foo::FOO = 42; // definition
Run Code Online (Sandbox Code Playgroud)

你在这里有什么:

static int counter = 0;
Run Code Online (Sandbox Code Playgroud)

是一个静态变量,它不是任何类的静态成员。它只是非成员静态变量,静态到CDummy.cpp.