簡體   English   中英

更改類變量時遇到麻煩

[英]Trouble changing class variable

我正在嘗試編寫一個小游戲,其中盒子從窗口的頂部放下。 但是由於某種原因,我無法在類中更改內部變量y坐標。 我不知道我是否缺少基本的知識,但找不到錯誤。

盒子

#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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM