未定义的引用,使用SFML 我已经开始学习C++的SFML,不理解在ReDelWindows环境下使用和和 */COD>的规则。你能帮我吗

未定义的引用,使用SFML 我已经开始学习C++的SFML,不理解在ReDelWindows环境下使用和和 */COD>的规则。你能帮我吗,c++,pointers,sfml,C++,Pointers,Sfml,主要类别: #include <SFML/Graphics.hpp> #include "Square.h" int main() { sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!"); Square sq(5,5); while (window.isOpen()) { sf::Event event; while (window.poll

主要类别:

#include <SFML/Graphics.hpp>
#include "Square.h"

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    Square sq(5,5);

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

        window.clear();
        sq.draw(&window);
        window.display();
    }

    return 0;
}
方形类:

#include <SFML/Graphics.hpp>
class Square{
    sf::RectangleShape rectangle;

    int y;
    int x;
    public:
        Square(int coordX, int coordY)
        : rectangle(), y(coordY),x(coordX)
        {
            rectangle.setSize(sf::Vector2f(10,100));
            rectangle.setOrigin(5,50);
        }
        Square()
        : rectangle(), y(5),x(5)
        {
            rectangle.setSize(sf::Vector2f(10,100));
            rectangle.setOrigin(5,50);
        }
        void draw(sf::RenderWindow* target)
        {
            target->draw(rectangle);
        }

如何使其工作?

删除square.cpp并将square.h文件更改为以下内容。在更改文件之前,请确保进行备份

#ifndef SQUARE_H
#define SQUARE_H
class Square
{
    private:
    sf::RenderWindow* window;
    sf::RectangleShape rectangle;
    int y;
    int x;
    public:
        Square(int coordX, int coordY)
        : rectangle(), y(coordY),x(coordX)
        {
            rectangle.setSize(sf::Vector2f(10,100));
            rectangle.setOrigin(5,50);
        }
        Square()
        : rectangle(), y(5),x(5)
        {
            rectangle.setSize(sf::Vector2f(10,100));
            rectangle.setOrigin(5,50);
        }
        void draw(sf::RenderWindow* target)
        {
            target->draw(rectangle);
        }
};

#endif
在C++中,你有函数声明和函数定义:

实施:

// X.cpp
#include "X.h"
void X::foo() { ...code .... }

// here you wrote
// class X { void foo(){} };
// which is a _declaration_ of class X
// with an _inline definition_ of foo.
用法:

// main.cpp
#include "X.h"
将此模式应用于代码应确保

  • 每个符号都有定义
  • 没有多次定义符号

您是否将square.h包含在square.cpp中?是的,现在的错误是:square.cpp:4:7重新初始化«类square»square.h:3:7:上次初始化«类square»我将“;”在头中的#endif之前,并在.cpp中删除,这是因为您在square.cpp中重新声明了类。您只需要提供函数实现,而不是重新定义所有内容。耶!我做到了!谢谢。
// X.cpp
#include "X.h"
void X::foo() { ...code .... }

// here you wrote
// class X { void foo(){} };
// which is a _declaration_ of class X
// with an _inline definition_ of foo.
// main.cpp
#include "X.h"