我有一个我似乎无法理解的问题,对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::WIDTH
。这就像Java中的公共静态变量。如果每个Smoke对象都需要自己的宽度,则需要告诉粒子对象它需要哪一个Smoke,或者将WIDTH和HEIGHT传递给Particle构造函数。