在C++中使用头文件时如何以及在何处定义类变量
How and where to define class variable when using header files in C++
/*
* 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;
在这里,您可以阅读有关如何在类声明中使用静态变量的更多信息。
相关文章:
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何避免在仅标头库中C++类/变量重定义
- c++ 在非类函数中使用类变量
- 在派生类中使用基类的私有成员变量的最佳方法
- 变量如何以及在何处可能没有C++关联的名称?
- 无法在具有常量变量大小的类中创建堆栈分配数组
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 在何处放置与类方法相关的帮助程序函数C++
- 如何在公共类方法中初始化公共变量
- 如何在模板类中设置静态常量变量
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- 在没有类定义的标头中定义成员变量
- 如何在构造函数中访问类变量以分配它们,而无需在C++中使用此指针
- memcpy() 在一个类中被调用以复制到另一个类变量中后会引发异常
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- Google Mock:在目标类的构造函数中实例化的模拟私有变量成员
- 如何在模板类中返回成员变量的副本
- 在C++中使用头文件时如何以及在何处定义类变量
- 将派生类对象存储在基类变量中