2014-10-16 30 views
0

我正在嘗試創建一個包含點基元的struct以及一個繪製它的方法。但是,在方法之外聲明sf::VertexArray似乎不起作用。在一個方法中完全相同的聲明完美無缺。這裏是代碼示例和錯誤。 SFML版本2.1類中的VertexArray聲明

編輯:在這兩種情況下都使用using namespace std;

作品:

struct Point 
{ 
    int dot_x, dot_y; 
    sf::Color dot_color; 
    Point (int x = 50, int y = 50, sf::Color color = sf::Color::Green) { 
     dot_color = color; 
     dot_x = x; 
     dot_y = y; 
    } 
    virtual void draw() { 
     sf::VertexArray dot(sf::Points, 1); 
     dot[0].position = sf::Vector2f(dot_x,dot_y); 
     dot[0].color = dot_color; 
     window.draw(dot); 
    } 
}; 

是否工作:

struct Point { 
    sf::VertexArray dot(sf::Points, 1); 
    Point (int x = 50, int y = 50, sf::Color color = sf::Color::Green) { 
     dot[0].position = sf::Vector2f(x,y); 
     dot[0].color = color; 
    } 
    virtual void draw() { 
     window.draw(dot); 
    } 
}; 

錯誤(所有指着VertexArray聲明字符串):

E:\CodeBlocks\Labs\sem3\sfml1\main.cpp|64|error: 'sf::Points' is not a type| 
E:\CodeBlocks\Labs\sem3\sfml1\main.cpp|64|error: expected identifier before numeric constant| 
E:\CodeBlocks\Labs\sem3\sfml1\main.cpp|64|error: expected ',' or '...' before numeric constant| 
+0

你能給一個指針請,這些線路實際上是'的main.cpp | 64 |'?你可能想錯過一些額外的頭文件嗎? – 2014-10-16 21:21:36

+0

'sf :: VertexArray dot(sf :: Points,1);'在非工作版本中是有問題的行。如果我錯過了標題,我認爲該程序不適用於任何一種變體。 – fwiffo 2014-10-16 21:22:58

回答

0
sf::VertexArray dot(sf::Points, 1); 

這是一個帶有初始化變量的聲明:只能在名稱空間或函數範圍內寫入這些變量。解析器是適當的混淆,因爲你已經在你的類範圍中。它基本上試圖將其解析爲函數聲明,但由於sf::Points1都不是類型,所以這種方法最終也會失敗。

你應該這裏使用構造的成員初始化器列表:

struct Point 
{ 
    sf::VertexArray dot; 

    Point (int x = 50, int y = 50, sf::Color color = sf::Color::Green) 
     : dot(sf::Points, 1) 
    { 
     dot[0].position = sf::Vector2f(x,y); 
     dot[0].color = color; 
    } 

    virtual void draw() 
    { 
     window.draw(dot); 
    } 
}; 
+0

謝謝,這已經解決了這個問題。 因此,如果我必須使用帶參數的構造函數初始化一個變量,那麼聲明不帶參數的變量並從別處執行其構造函數(包含類的構造函數或其他方法之一)是正確的路徑? – fwiffo 2014-10-16 21:48:59

+0

@fwiffo:基本上是的 – 2014-10-16 21:58:41