我的功能链不想工作,为什么?

时间:2010-01-03 15:28:34

标签: c++

我有以下课程:

GLRectangle.h

#include "XPView.h"

class GLRectangle
{
public:
    int top, left, bottom, right;

public:
    GLRectangle(void);
    ~GLRectangle(void);
    GLRectangle* centerRect(int rectWidth, int rectHeight, int boundWidth=0, int boundHeight=0);
};

GLRectangle.cpp

#include "GLRectangle.h"

GLRectangle::GLRectangle(void)
{
}

GLRectangle::~GLRectangle(void)
{
}

GLRectangle* GLRectangle::centerRect(int rectWidth, int rectHeight, int boundWidth, int boundHeight)
{
    if(boundWidth == 0)
    {
        boundWidth = XPView::getWindowWidth();
    }

    if(boundHeight == 0)
    {
        boundHeight = XPView::getWindowHeight();
    }

    // Set rectangle attributes
    left   = boundWidth / 2 - rectWidth / 2;
    top    = boundHeight / 2 + rectHeight / 2;
    right  = boundWidth / 2 + rectWidth / 2;
    bottom = boundHeight / 2- rectHeight / 2;

    return this;
}

我试图将一个函数链接到对象的构造上,如下所示:

wndRect = new GLRectangle()->centerRect(400, 160);

但收到以下错误:

error C2143: syntax error:missing ';' before '->'

有没有办法让它发挥作用?

2 个答案:

答案 0 :(得分:2)

这是一个operator precedence问题。尝试

// Add some brackets
wndRect = (new GLRectangle())->centerRect(400, 160);

答案 1 :(得分:1)

(wndRect = new GLRectangle())->centerRect(400, 160);

但为什么这样呢?为什么不为构造函数提供参数,以便您可以说:

wndRect = new GLRectangle( 400, 160 );