【发布时间】:2018-12-12 01:01:02
【问题描述】:
我有一个 Rect 类,它保存形状的宽度、高度、x 和 y 值。该类可以使用参数中的值进行绘制并移动绘制的矩形。
Rect::Rect(w, h, x, y, const std::string &image_path) : _w(w), _h(h),
_x(x), _y(y)
{
SDL_Surface *surface = IMG_Load(image_path.c_str());
if (!surface) {
std::cerr << "Failed to create surface.";
}
//create texture
texture = SDL_CreateTextureFromSurface(Window::renderer, surface);
if (!texture) {
std::cerr << "Failed to create worker texture.";
}
SDL_FreeSurface(surface);
}
Rect::~Rect()
{
SDL_DestroyTexture(texture);
}
Rect::draw()
{
//where the constructor parameters are parsed
SDL_Rect rect= {_x, _y, _w, _h} ;
//extra code about some SDL texture stuff and RenderCopy
}
Rect::moveX(int x){
_x +=x;
}
在我的 Unit 类中,我包含 Rect 类并创建我的单位,在同一个函数中绘制它们。 unit 中还有另一个函数,它通过检查另一个类中发生变化的另一个值来移动 rect。
Unit::Unit()
Unit::~Unit()
void Unit::createUnit(int type, int x, int y){
if (type == 0)
{
Rect unit1(unitImageWidth, unitImageSizeHeight, x, y, "res/unit1.png");
}
if (type == 1)
{
Rect unit2(unitImageWidth, unitImageSizeHeight, x, y, "res/unit2.png");
}
}
void Unit::moveUnit(int x){
if(selection == 0)
{
unit1.movex(x);
}
if (selection == 1)
{
unit2.movex(x);
}
}
我的问题是:
在Unit::moveUnit()中,如何引用Unit::createUnit()中初始化的对象Rect"unit1"和Rect"unit2" >?
当我尝试编译时,它说 unit1 和 unit2 未定义。
【问题讨论】:
-
unit1和unit2是局部变量。它们不存在于它们包含的{}块之外。 -
那些是局部变量。一旦超出范围,它们就会消失。您需要创建范围更广的变量,可能是类成员变量。