2013-12-09 53 views
0

我已经开始学习SFML与C++同时并且不理解在RenderWindow情况下使用&*的规则。你可以帮帮我吗?未定义的引用,使用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.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类:

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

#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的画一个正方形

我该如何做这项工作?

+0

是否包含square.h在square.cpp更明确? –

+0

是的,现在的错误是: square.cpp:4:7re-initializing«class Square» square.h:3:7:以前初始化«class Square» 我把';'在#endif标题之前,并在.cpp中删除 – amazingbasil

+0

这是因为您正在square.cpp中重新声明该类。你只需要提供函数实现,而不是重新定义一切。 –

回答

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" 

应用这种模式对你的代码应该确保

  • 每一个符号定义
  • 没有符号不止一次
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