gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:29 25 4
gpt4 key购买 nike

/*
* 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--;
}

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

谢谢

最佳答案

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

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

Foo.h

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

Foo.cpp

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

这里有什么:

static int counter = 0;

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

关于c++ - 在 C++ 中使用头文件时如何以及在何处定义类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17342703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com