【问题标题】:expected initializer before ‘*’ token“*”标记之前的预期初始化程序
【发布时间】:2013-02-06 04:08:02
【问题描述】:

我正在尝试实现 Design Patterns 书中的代码。我收到以下错误:

expected initializer before ‘*’ token

对于这一行:

static Singleton *Singleton::itsInstance = 0;

这是完整的代码。我正在使用 g++ 4.2.1 来尝试编译它。

class Singleton {
public:
    static Singleton *instance();
protected:
    Singleton();
private:
    static Singleton *itsInstance;
}

static Singleton *Singleton::itsInstance = 0;

Singleton *Singleton::instance()
{
    if (!itsInstance)
    {
        itsInstance = new Singleton;
    }
    return itsInstance;
}

有什么想法吗?

【问题讨论】:

  • 您在类定义后缺少一个分号。此外,您不需要在定义之前使用 static 这个词。
  • 赛斯是对的。但是,当我们继续工作时 - 您可能应该在分配之前将 0 转换为指针。
  • @BrianCain 从NULL0nullptr 分配时不需要强制转换。
  • 从定义中删除“静态”(在类下方)。这是非法的。并且已经指出了类声明末尾缺少的分号。
  • 您可能需要检查:stackoverflow.com/a/1008289/14065

标签: c++ design-patterns


【解决方案1】:
class Singleton {

};
 ^^^

这个!还有,

static Singleton *Singleton::itsInstance = 0;

替换为:

Singleton *Singleton::itsInstance = 0;

你需要static 只在声明上而不是在定义上。

【讨论】:

  • 啊啊!谢谢,就是这样。
【解决方案2】:

您的类定义后缺少分号,并且您不想要static

static Singleton *Singleton::itsInstance = 0;

应该是

Singleton *Singleton::itsInstance = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多