未定义的引用,使用SFML

时间:2013-12-09 14:04:44

标签: c++ pointers sfml

我已经开始在与C ++同时学习SFML,并且不理解在RenderWindow案例中使用&*的规则。你能帮帮我吗?

主要课程:

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

方头:

#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);
        Square();
        void draw(const sf::RenderWindow* target);
};

#endif

Square class:

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

我无法在RenderWindow上绘制正方形:

main.cpp:(.text+0x17d): undefined reference to `Square::Square(int, int)'
main.cpp:(.text+0x211): undefined reference to `Square::draw(sf::RenderWindow const*)'

我该如何做到这一点?

2 个答案:

答案 0 :(得分:0)

删除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

答案 1 :(得分:0)

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

// declaration, typically in X.h
#pragma once // don't include this twice, my dear compiler
class X {
public:
   void foo();
};

实现:

// 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"

将此模式应用于您的代码应该确保

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