更改类变量的麻烦
Trouble changing class variable
我正在尝试写一个小游戏,其中盒子从窗口顶部下降。但是由于某种原因,我无法更改班级的内部变量,即y坐标。我知道如果我缺少一些基本的东西,但是找不到错误。
box.h
#pragma once
#include "SDL.h"
class Box
{
public:
Box();
~Box();
void setX (int a);
void setY (int a);
void setSpeed (int a);
void setSurface ();
void render(SDL_Surface *source, SDL_Window *win);
void update();
private:
int x;
int y;
int speed;
SDL_Surface *sur;
SDL_Rect rect;
};
box.cpp
#include "Box.h"
#include "SDL_image.h"
#include <iostream>
void Box::setX(int a)
{
x = a;
}
void Box::setY (int a)
{
y = a;
}
void Box::setSpeed (int a)
{
speed = a;
}
void Box::setSurface()
{
sur = IMG_Load("C:/hello.bmp");
if (sur == NULL)
{
std::cout << IMG_GetError();
}
}
Box::Box()
{
speed = 5;
y = 0;
x = 3;
rect.x = 0;
rect.y = 0;
}
Box::~Box()
{
}
void Box::render(SDL_Surface *source, SDL_Window *win)
{
SDL_BlitSurface(sur, NULL, source, &rect);
SDL_UpdateWindowSurface(win);
}
void Box::update()
{
setY(y + speed); //I've also tried y = y + speed
rect.y = y;
}
main.cpp
#include "SDL.h"
#include "Box.h"
#include "SDL_image.h"
#include <iostream>
bool init();
void update(Box test);
void render(Box test);
SDL_Window *win;
SDL_Surface *source;
int main(int argc, char *argv[])
{
init();
bool quit = false;
SDL_Event e;
Box test;
test.setSurface();
test.render(source, win);
while (quit ==false)
{
while( SDL_PollEvent( &e ) != 0 )
{
if( e.type == SDL_QUIT )
{
quit = true;
}
}
update(test);
render(test);
}
return 0;
}
void update(Box test)
{
test.update();
}
void render(Box test)
{
test.render(source, win);
}
bool init()
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (win == NULL)
{
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
return 1;
}
source = SDL_GetWindowSurface(win);
return true;
}
update
按值采用其 Box
参数,因此当调用 update(test)
时,总是制作原始 Box
的副本。然后对此副本进行修改,并且原始副本保持不变。要解决此问题,请通过参考进行update
进行参数。
void update(Box& test);
void update(Box& test)
{
test.update();
}
相关文章:
- 查找后更改类变量
- 如何避免在仅标头库中C++类/变量重定义
- c++ 在非类函数中使用类变量
- 基于模板的类变量
- 分段 访问私有类变量时出错
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如何访问基类向量中的子类变量?(对于实体组件系统)
- 模板类变量作为非模板类的成员
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- 如何在构造函数中访问类变量以分配它们,而无需在C++中使用此指针
- 类变量无法从类方法访问
- 指针作为类变量 Qt
- 为什么线程对类变量所做的更改没有影响?
- memcpy() 在一个类中被调用以复制到另一个类变量中后会引发异常
- C++:使用基类中的仅派生类变量
- 从静态成员函数访问私有非静态类变量 - C++
- 静态类变量的多重定义
- 使用 WindowSetup 类变量获取错误
- 更改类变量的麻烦
- 在使用头文件/源文件时访问类变量的麻烦