SFML C++ 为什么屏幕上什么也没有画? (简单代码)

SFML C++ why is nothing drawn on screen here? (simple code)

这是我在 C++ 中使用 SFML 库的示例程序。我想创建一个自定义函数 'draw_func',它在提供的坐标处绘制一些东西(如本例中的矩形)。我将 return 变量的类型设置为 sfml 对象矩形(这是我 return 和我绘制的)但是屏幕是黑色的。

#include <iostream>
#include <math.h>
#include "SFML/OpenGL.hpp"
#include <SFML/Graphics.hpp>

sf::RectangleShape draw_func(int x, int y)
{
    sf::RectangleShape rect(sf::Vector2f(200, 100));
    rect.setPosition(x, y);
    rect.setFillColor(sf::Color((0, 0, 255)));
    return rect;
}


int main()
{

    int height = 400;
    int length = 400;
    int pos_x = 0;
    int pos_y = 0;

    sf::RenderWindow window(sf::VideoMode(length, height), "My window");

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color::Black);

        sf::RectangleShape rectangle = draw_func(pos_x, pos_y);
        window.draw(rectangle);
        window.display();
    }

}

我认为问题出在这位政治家身上:

rect.setFillColor(sf::Color((0, 0, 255)));

双括号实际上解析为单个值,0 因为:

sf::Color((0, 0, 255))

构造一个值为0sf::Color因为

(0, 0, 255) 

不是 函数参数,因为有额外的括号它是一个 表达式 涉及 逗号运算符 :

0, 0, 255 

逗号运算符 始终具有其最左边 表达式的值。在这种情况下 0.

现在 sf::Color 有一个接受单个值的构造函数:

sf::Color(Uint32 color);

您正在创建 黑色 sf::Color(0).