小编Kef*_*fir的帖子

C++标头或.cpp中的类变量声明?

到目前为止,我一直在使用以下方式的类:

GameEngine.h声明该类如下

class GameEngine {
public:
    // Declaration of constructor and public methods

private:
    InputManager inputManager;
    int a, b, c;

    // Declaration of private methods
};
Run Code Online (Sandbox Code Playgroud)

我的GameEngine.cpp文件然后只是实现方法

#include "____.h"    
GameEngine::GameEngine() {

}

void GameEngine::run() {
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

但是,我最近读到变量声明不应该在头文件中.在上面的例子中,这将是一个inputManager和a,b,c.

现在,我一直在寻找放置变量声明的位置,我找到的最接近的答案是:头文件中的变量声明

但是,我不确定extern的使用是否有意义; 我只是声明私有变量,它们只会在类本身的实例中使用.我的头文件中的变量声明是否正常?或者我应该把它们放在别处吗?如果我把它们放在cpp文件中,它们会直接进入#include吗?

c++ header-files variable-declaration

5
推荐指数
2
解决办法
2万
查看次数

数组元素的本地副本

为了使我的代码更具可读性,我在函数内部有一个局部变量,它接受一个数组中的指定元素,如下所示:

Element* elements = new Element[10];

void doSomething(int index) {
    Element element = elements[index];
    // do things with that element
}
Run Code Online (Sandbox Code Playgroud)

这里发生了什么:元素是元素[index]的独立副本,在函数结束时被销毁?从我测试的内容来看,似乎是因为元素的变化不会影响元素[index],但是,我想知道幕后发生了什么.元素的赋值是否调用隐式复制构造函数?

c++ arrays

2
推荐指数
1
解决办法
82
查看次数

标签 统计

c++ ×2

arrays ×1

header-files ×1

variable-declaration ×1