【问题标题】:Use Class Member Function Pointer before Class Definition C++在类定义 C++ 之前使用类成员函数指针
【发布时间】:2021-01-15 16:04:52
【问题描述】:

我有以下代码:

// FILE_NAME: compiler.h

typedef enum Precedence { /* ENUM MEMBERS */ } Precedence;
typedef enum TokenType { /* ENUM MEMBERS */ } TokenType;

typedef void (Compiler::*ParseFn)();

typedef struct ParseRule {
    ParseFn prefix;
    ParseFn infix;
    Precedence precedence;
} ParseRule;

class Compiler {
    public:
        std::unordered_map<TokenType, ParseRule> rules;
        ParseRule getRule(TokenType type) {
            return rules[type];
        };
        void binary();
        void unary();
};

我正在尝试定义一个哈希映射,它将TokenType 的键映射到具有结构ParserRule 形式的值。

Compiler::rules hashmap 的键值对示例如下:

rules[TOKEN_MINUS] = {unary, binary, PREC_TERM}

当我尝试使用 C++11 进行编译时,我收到以下错误以及许多其他错误:

./compiler/compiler.h:58:15: error: use of undeclared identifier 'Compiler'
typedef void (Compiler::*ParseFn)();

这是有道理的,因为我试图在定义 Compiler 类之前使用类 Compiler 来定义类型 ParseFn

我对 C/C++ 编码非常陌生(几周前我开始学习),所以我想知道是否有另一种方法可以定义类型和类而不会导致编译器错误。

【问题讨论】:

  • 这并没有解决问题,但是在 C++ 中你不必跳 typedef enum Precedence { ... } Precedence; 舞。那是C的事情。在 C++ 中,enum Precedence { ... }; 就足够了。

标签: c++ class typedef


【解决方案1】:

在引用 Compiler 之前,您需要(预先)声明为一个类:

class Compiler;

typedef void (Compiler::*ParseFn)();

【讨论】:

  • 成功了,非常感谢!我想这样做很多次,但感觉就像我在声明两次类,我想这会引发错误。
  • 只要声明匹配,您可以根据需要多次声明。您只能定义它们一次。
猜你喜欢
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 2015-12-05
相关资源
最近更新 更多