简体   繁体   English

在 Class 定义 C++ 之前使用 Class 成员 Function 指针

[英]Use Class Member Function Pointer before Class Definition C++

I have the following code:我有以下代码:

// 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();
};

I am trying to define a hashmap that maps a key of TokenType to a value that has the form of the struct ParserRule .我正在尝试定义一个 hashmap ,它将TokenType的键映射到具有结构ParserRule形式的值。

An example of a key-value pair for the Compiler::rules hashmap is as follows: Compiler::rules hashmap 的键值对示例如下:

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

When I try to compile with C++11, I get the following error, plus many others:当我尝试使用 C++11 进行编译时,出现以下错误以及许多其他错误:

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

This makes sense since I am trying to use the class Compiler to define the type ParseFn before the Compiler class has been defined.这是有道理的,因为我试图在定义Compiler ParseFn之前使用 class Compiler来定义 ParseFn 类型。

I am very new to coding in C/C++ (I started learning a couple of weeks ago), so I was wondering if there is another way of defining the types and classes without causing a compiler error.我对 C/C++ 编码非常陌生(几周前我开始学习),所以我想知道是否有另一种方法来定义类型和类而不会导致编译器错误。

You need to (pre-)declare Compiler as a class before referring to it:在引用它之前,您需要(预先)将Compiler声明为 class:

class Compiler;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM