c++ - 一组类如何使用变量?

标签 c++ variables class scope

我有一个我似乎无法理解的问题,因为它对 C++ 来说是相当新的。我有一个类,其中一组变量在 .h 文件中声明,然后在 .cpp 文件中初始化。这些相同的变量被一组 3 个其他类使用 - 编译器将它们视为超出范围。我不确定如何链接类,以便所有类都可以看到变量。代码本身是基于 Java 的语言的移植。我使用 openFrameworks 作为我的开发环境,如果有帮助的话,我将我的编译器错误发布到那里的论坛上 http://www.openframeworks.cc/forum/viewtopic.php?f=8&t=4505

smoke.h

#pragma once

#ifndef SMOKE
#define SMOKE

#include "ofMain.h"
#include "VSquare.h"
#include "VBuffer.h"
#include "Particle.h"

#define LWIDTH 151
#define LHEIGHT 11

class Smoke {
public:
int WIDTH;
int HEIGHT;

int RES;
int PENSIZE;


int PNUM;


VSquare v [LWIDTH] [LHEIGHT] ;
VBuffer vbuf [LHEIGHT][LHEIGHT] ;

Particle p [30000];

int pcount;
int mouseXvel;
int mouseYvel;

int randomGust;
int randomGustMax;
float randomGustX;
float randomGustY;
float randomGustSize;
float randomGustXvel;
float randomGustYvel;

Smoke();

void init();
void draw();

};
#endif

我的 .cpp 文件中的代码如下所示:

#include "Smoke.h"


Smoke::Smoke(){
WIDTH = 300; //these are the variables that go out of scope in all other classes
HEIGHT = 300;

RES = 2;
PENSIZE = 30;


PNUM = 30000;

pcount = 0;
mouseXvel = 0;
mouseYvel = 0;

randomGust = 0;
}

还有一个我遇到问题的类:

Particle.h

#ifndef PARTICLE
#define PARTICLE

#include "ofMain.h"


class Particle{
public:
float x;
float y;
float xvel;
float yvel;
float temp;
int pos;

Particle(float xIn = 0, float yIn = 0);

void reposition();
void updatepos();



};
#endif

以及抛出错误的 .cpp 文件(摘录):

#include "Particle.h"

Particle::Particle(float xIn, float yIn){
x = xIn;
y = yIn;

}

void Particle::reposition() {
x = WIDTH/2+ofRandom(-20,20); //eg, WIDTH and HEIGHT not declared in this scope
y = ofRandom(HEIGHT-10,HEIGHT);

xvel = ofRandom(-1,1);
yvel = ofRandom(-1,1);
}

void Particle::updatepos() {
int vi = (int)(x/RES); //RES also not declared in this scope
int vu = (int)(y/RES);

if(vi > 0 && vi < LWIDTH && vu > 0 && vu < LHEIGHT) {
v[vi][vu].addcolour(2);
//and so on...

真心希望大家能帮我解决这个问题!非常感谢

最佳答案

如果 WIDTH 和 HEIGHT 应该是常量,您可以将它们移出 Smoke 并将它们声明为常量:const int WIDTH = 300; 如果它们需要成为 Smoke 的成员但是仍然是常量,然后只需将它们声明为 static const int WIDTH = 300 然后在 Particle.cpp 中将它们声明为 #include "Smoke.h" 并将其引用为 Smoke::宽度。这就像 Java 中的公共(public)静态变量。如果每个 Smoke 对象都需要自己的宽度,那么您需要告诉 Particle 对象它需要哪个 Smoke,或者将 WIDTH 和 HEIGHT 传递给 Particle 构造函数。

关于c++ - 一组类如何使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3588727/

相关文章:

不同类中的 Python 3 tkinter 按钮命令

html - 向 'active' 和 'non-active' 图形类添加不同的不透明度

c++ - 非标量类型子类错误

c++ - std::any 由 std::exception_ptr

c++ - SDL_GL_SetAttribute 不设置颜色大小

c++ - 基于二维数组初始化 vector

c - gcc 将临时变量定义为函数参数

c++ - 如何在屏幕上的随机位置绘制一个字符 - C++

php - 排序然后设置变量

mysql - 为什么我的简单 sql 查询不起作用?