【问题标题】:Builder implementation构建器实现
【发布时间】:2013-11-24 23:44:30
【问题描述】:

我正在尝试通过使用“piggyback”方法调用方法在 C++ 中实现构建器,但 Visual C++ 编译器会抛出错误提示:

Error 6 error C2143: syntax error : missing ';' before '->' c:\users\owner\desktop\user\t\t\algebratopic.cpp 20 1 MathTutor

使用以下代码:

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

每次调用 with* 方法,返回问题构建器实例,而 buildQuestion 返回一个 question* 对象。

有什么想法吗?

【问题讨论】:

  • 没有解决问题
  • 你为什么在这里使用手动内存管理(和泄漏内存)?此外,此代码显然不足以诊断代码。发布一个最小的工作示例来说明问题。

标签: c++ visual-studio-2010 oop visual-c++


【解决方案1】:

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

struct Foo
{
    Foo & f() { return *this; }
    Foo & g() { return *this; }
    Foo * build() { return this; }
};

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2018-03-17
    • 2020-07-06
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多