参数类型与指针/引用不匹配

parameter type mismatch with pointer/reference

本文关键字:引用 不匹配 指针 类型 参数      更新时间:2023-10-16

我正在尝试将玩家添加到我正在创建的游戏中,但在此过程中,当我在mainGame.cpp中创建新玩家时,我一直在窗口参数上获得错误

这个问题是一个指针/引用问题,但我不知道如何解决它。

这是错误信息:

参数类型不匹配:不兼容类型'sf::RenderWindow &'和'sf::RenderWindow *'

my mainGame.cpp如下:

void mainGame::Initialize(sf::RenderWindow* window){
    this->player = new Player(20,100, config, window);
}
void mainGame::Destroy(sf::RenderWindow* window){
    delete this->player;
}

my mainGame.h file:

class mainGame : public tiny_state{
public:
    void Initialize(sf::RenderWindow* window);
    void Destroy(sf::RenderWindow* window);
protected:
    Player& player;
    Config config;
    sf::RenderWindow window;
};

my Plyer.cpp file:

Player::Player(float x, float y, const Config& config, sf::RenderWindow& )
    : x(x), y(y),
    config(config),
    window(window)
{
    rectangle.setSize(sf::Vector2f(sizeWidth, sizeHeight));
    rectangle.setFillColor(sf::Color::White);
}
void Player::move(float delta){
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
        y -= speed * delta;
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        y += speed * delta;
    y = std::max(y, 0.f);
    y = std::min(y, (float)(config.screenheight - sizeHeight));
}
void Player::draw(){
    rectangle.setPosition(x, y);
    window.draw(rectangle);
}

my player.h file:

struct Player{
    Player(float x, float y, const Config& config, sf::RenderWindow& window);
    void move(float delta);
    void draw();
    const int sizeHeight = 100;
    const int sizeWidth = 10;
    const float speed = 5;
    float x, y;
    sf::RectangleShape rectangle;
    const Config& config;
    sf::RenderWindow& window;
};

你传递了一个指针,在这里需要引用。废弃:

this->player = new Player(20,100, config, *window);
                                          ^
顺便说一下,考虑使用智能指针,比如unique_ptr来管理内存。这样你就可以使用0/3/5规则,而不是打破3/5规则的一部分。