【问题标题】:what is Base*(*)()什么是 Base*(*)()
【发布时间】:2012-08-05 13:49:40
【问题描述】:

有人可以为我解释一下 Base*(*)(),如下所示:

typedef std::map<std::string, Base*(*)()> map_type;

如何从函数中返回它?

我假设它是一个函数指针,返回一个Base*,但这是什么(*)。

我在以下 SO 帖子 Is there a way to instantiate objects from a string holding their class name? 中发现了这一点

谢谢

【问题讨论】:

  • cdeclBase*(*)() 是一个语法错误,有趣。
  • @FredOverflow:我认为我们必须假设 Base 被定义为一种类型。
  • @FredOverflow:建立一个抽象基类。

标签: c++ templates stl


【解决方案1】:

Base* (*)() 是一种类型:指向返回 Base* 的函数的指针。 * 表示它是一个指针,() 用于覆盖优先级以确保指针适用于函数本身而不是返回类型。

您可以通过返回适当类型的函数名称从函数中返回它。

例如

Base* f();

Base* (*g())()
{
    return f;
}

【讨论】:

    【解决方案2】:

    是签名Base*()的函数指针的类型:

    Base * foo();
    
    Base * (*fp)() = &foo;
    

    或者在你的情况下:

    map_type callbacks;
    callbacks["Foo"] = &foo;
    

    调用:

    Base * p = callbacks["Foo"]();  // same as "p = foo();"
    

    【讨论】:

    • 感谢您的帮助,很遗憾,由于缺少积分,我无法为您的答案投票。
    猜你喜欢
    • 2011-04-23
    • 2015-09-17
    • 2013-08-11
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    相关资源
    最近更新 更多