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

How and where to define class variable when using header files in C++

本文关键字:在何处 类变量 定义 C++ 文件      更新时间:2023-10-16
/*
 * CDummy.h
 */
#ifndef CDUMMY_H_
#define CDUMMY_H_
class CDummy {
public:
    CDummy();
    virtual ~CDummy();
};
#endif /* CDUMMY_H_ */

我已经读过不应该在头文件中声明类变量。 对吗?所以我在下面的 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--;
}

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

感谢

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

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

福.h

struct Foo
{
  void foo() const;
  static int FOO;   // declaration
};

福.cpp

void Foo::foo() {}
int Foo::FOO = 42; // definition

你在这里有什么:

static int counter = 0;

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

静态 int 计数器 = 0;//所以这是我的静态计数器。 这是现在私有的还是公共的? 我怎样才能公开它,我不能在这里引入公共块。

从我看到的代码中counter只是一个全局静态变量,因为它没有在您的CDummy任何地方被描述

静态变量应该是公共的,以便您可以在类声明之外初始化它们。您的代码应如下所示才能公开:

class CDummy {
public:
   static int count;
   CDummy();
   virtual ~CDummy();
};
// inside CDummy.cpp
int CDummy::count = 0;

在这里,您可以阅读有关如何在类声明中使用静态变量的更多信息。