生成器实现

Builder implementation

本文关键字:实现      更新时间:2023-10-16

我正试图通过使用"piggyback"方法调用方法在C++中实现一个生成器,但Visual C++编译器抛出一个错误:

Error 6 error C2143: syntax error : missing ';' before '->' c:usersownerdesktopuserttalgebratopic.cpp 20 1 MathTutor

使用以下代码:

Question * test = new QuestionBuilder()
        ->withQuestionText("(4y + 5x)2 = ")
        ->withCorrectAnswer("16y2 + 25x2 + 40xy")
        ->buildQuestion();

每次对with*方法的调用都返回问题生成器实例,buildQuestion返回一个question*对象。

有什么想法吗?

new表达式周围加括号,并根据需要将->更改为.。例如:

struct Foo
{
    Foo & f() { return *this; }
    Foo & g() { return *this; }
    Foo * build() { return this; }
};
int main()
{
    Foo * p = (new Foo())->f().g().build();
}