2013-12-09 100 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