首页 > 解决方案 > C++ 和 SFML,重载函数“sf::RenderWindow.draw()”的实例不匹配参数列表

问题描述

我目前正在尝试用 C++ 中的 SFML 制作一个简单的乒乓球游戏。我一直在主文件中得到错误。

#include <iostream>
#include "Ball.h"

Ball b;

int main()
{
    // create the window
    sf::RenderWindow window(sf::VideoMode(1200, 600), "My window");

    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
            window.close();
        }

        // clear the window with black color
        window.clear(sf::Color::Black);

        // draw everything here...
        window.draw(b);

        // end the current frame
        window.display();
    }

    return 0;
}

这是 ball.h 文件:

#pragma once
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class Ball
{
public:
    double x, y;
    int Radius;

    void Render(int Rad, sf::Color BallColour) {
        sf::CircleShape shape(Rad);
        // set the shape color to green
        shape.setFillColor(BallColour);
    }
};

我不确定为什么会发生错误。任何帮助,将不胜感激。

标签: c++sfml

解决方案


你没有调用渲染函数,你只是写了window.draw(b),程序不知道你是什么意思。在 Ball.h 中你应该写:

 #pragma once
    #include <iostream>
    #include <SFML/Window.hpp>
    #include <SFML/Graphics.hpp>
    class Ball
    {
    public:
        double x, y;
        int Radius;
    
        void Render(int Rad, RenderWindow& window) {
            sf::CircleShape shape(Rad);
            // set the shape color to green
            shape.setFillColor(sf::Color::Green);
            shape.setPosition(600, 300);//SETTING POSITION OF THE BALL
            window.draw(shape);//if you know what is reference on variable, you will understand what is it
        }
    };

在你的 main.cpp 中,你应该调用你的函数 Render:

#include <iostream>
#include "Ball.h"

int main()
{
    // create the window
    sf::RenderWindow window(sf::VideoMode(1200, 600), "My window");

    Ball b; //I advice you to create object of class in main function

    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
            window.close();
        }

        // clear the window with black color
        window.clear(sf::Color::Black);

        b.Render(10, window);// give the function reference on window

        // end the current frame
        window.display();
    }

    return 0;
}

推荐阅读