【问题标题】:Qualifier on function type .. has unspecified behavior函数类型的限定符 .. 具有未指定的行为
【发布时间】:2013-03-28 17:05:31
【问题描述】:
#ifndef SHAPEFACTORY_H_
#define SHAPEFACTORY_H_

#include <istream>
#include <map>
#include <string>

#include "shape.h"

typedef Shape *(createShapeFunction)(void);
/* thrown when a shape cannot be read from a stream */
class WrongFormatException { };

class ShapeFactory {

public:

    static void registerFunction(const std::string &string, const createShapeFunction *shapeFunction);
    static Shape *createShape(const std::string &string);
    static Shape *createShape(std::istream &ins);

private:

    std::map<std::string, createShapeFunction *> creationFunctions;
    ShapeFactory();
    static ShapeFactory *getShapeFactory();
};

#endif

这是标题,我还没有实现任何方法,但我收到以下警告:

Qualifier on function type 'createShapeFunction' (aka 'Shape *()') has unspecified behavior

ps:这个标题是我老师给的,作为作业我必须实现方法

【问题讨论】:

  • 你需要在第一组括号内有一个星号:typedef Shape* (*createShapeFunction)(void);
  • 就是这样。谢谢!
  • @metal,你能解释一下为什么会这样吗?
  • @Teodora 我已经在我的回答中解释过了。
  • 简而言之,第一组括号中的内容是类型的一部分,它需要是一个指针。函数指针的语法总是让我觉得有点奇怪。

标签: c++ factory


【解决方案1】:

这是一个愚蠢的警告信息。它不是未指定的,但您在 registerFunction 的第二个参数上添加的 const 限定将被忽略。

我们来看看createShapeFunctiontypedef

typedef Shape *(createShapeFunction)(void);

您可以将此类型理解为“一个不带参数并返回Shape* 的函数”。那么你就有了这种类型的参数:

const createShapeFunction*

这将是一个指向const 函数类型的指针。不存在const 函数类型,因此const 被忽略,参数类型等价于createShapeFunction*。也就是指向上面定义的函数类型的指针。

您的意思可能是 createShapeFunction 本身就是一个函数指针类型:

typedef Shape *(*createShapeFunction)(void);

现在您可以将此类型理解为“指向不带参数并返回 Shape* 的函数的指针”。那么这将使参数const createShapeFunction* 成为指向const 函数指针的指针。

【讨论】:

    【解决方案2】:

    发出警告是因为const createShapeFunction* 类型试图创建const 限定的函数类型(因为createShapeFunction 被定义为返回Shape* 并且不接受任何参数的函数类型)。这就是 C++11 标准对此的说法(第 8.5.3/6 段):

    函数声明器中 cv-qualifier-seq 的效果与在顶部添加 cv-qualification 不一样 的函数类型。在后一种情况下,将忽略 cv 限定符。 [注意:一个函数类型有一个 cv-qualifier-seq 不是 cv 限定类型;没有 cv 限定的函数类型。 ——尾注] [示例:

    typedef void F();
    struct S {
        const F f; // OK: equivalent to: void f();
    };
    

    ——结束示例]

    因此,编译器会警告您,您的意思可能不是您实际编写的内容,因为 const 函数类型的限定将被忽略。

    【讨论】:

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