gpt4 book ai didi

c++ - 更改类变量时遇到问题

转载 作者:行者123 更新时间:2023-11-28 00:34:39 24 4
gpt4 key购买 nike

我正在尝试编写一个小游戏,让盒子从窗口顶部掉落。但出于某种原因,我无法更改类中的内部变量,即 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) 被调用。然后修改此拷贝,并保持原件不变。要解决此问题,请使 update 通过引用获取其参数。

void update(Box& test);

void update(Box& test)
{
test.update();
}

关于c++ - 更改类变量时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21444825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com