如何访问 C++ 类中的前向声明?

问题描述 投票:0回答:1

下面的代码可以运行,但是将方法从这个状态机的每个状态中分离出来,可读性不是很好:

struct Base {
    virtual Base* next() = 0;
};

struct StateA : public Base {
    Base* next();
};

struct StateB : public Base {
    Base* next();
};

StateA stateA;
StateB stateB;

Base* StateA::next() {
    return &stateB;
}

Base* StateB::next() {
    return &stateA;
}

我宁愿有这种结构,不幸的是,我不知道在 C++ 中是否可以转发声明

stateA
stateB

struct Base {
    virtual Base* next() = 0;
};

struct StateA : public Base {
    Base* next() { return &stateB; }
};

struct StateB : public Base {
    Base* next() { return &stateA; }
};

StateA stateA;
StateB stateB;

是否有可能将

StateX
的实施与他们的声明一起保留?

我试图用这个来欺骗编译器,但正如猜测的那样,它没有构建:

struct Base {
    virtual Base* next() = 0;
};

struct StateA;
struct StateB;

extern StateA *stateAptr;
extern StateB *stateBptr;

struct StateA : public Base {
    Base* next() { return stateBptr; }
};

struct StateB : public Base {
    Base* next() { return stateAptr; }
};

StateA stateA;
StateB stateB;
StateA *stateAptr = &stateA;
StateB *stateBptr = &stateB;
c++ forward-declaration
1个回答
0
投票

关键字

extern
负责前向变量声明。但它可以在定义类型之前使用。您可以拆分成员函数声明和定义。

struct Base {
    virtual Base* next() = 0;
};

struct StateA : public Base {
    Base* next();
};

struct StateB : public Base {
    Base* next();
};

StateB stateB;
StateA stateA;

Base* StateA::next() { return &stateB; }
Base* StateB::next() { return &stateA; }

或者更新你使用

Base*
指针的技巧。

struct Base {
    virtual Base* next() = 0;
};

struct StateA;
struct StateB;

extern Base *stateAptr;
extern Base *stateBptr;

struct StateA : public Base {
    Base* next() { return stateBptr; }
};

struct StateB : public Base {
    Base* next() { return stateAptr; }
};

StateA stateA;
StateB stateB;
Base *stateAptr = &stateA;
Base *stateBptr = &stateB;

但是与第一个代码相比,它并没有提高可读性,并且与您的句子“它不是很可读”冲突。

© www.soinside.com 2019 - 2024. All rights reserved.