2014-10-16 19 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