C++ 类成员的循环引用

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

我有以下代码(为简洁起见,进行了简化)。我正在制作简单“程序”的解释器和执行器,它基本上由命令和循环组成。

class Command
{
    int code, arg; // whatever
};
class Loop;

using Statement = std::variant<std::monostate, Command, Loop>;

class Scope
{
    std::vector<Statement> statements;
public:
    Statement& appendCmd(const Command& = {}); // works
    Statement& appendLoop(const Loop& = {}); // cannot convert from 'initializer list' to 'const Loop &'
    Statement& appendLoop(const Loop& = Loop()); // use of undefined type 'Loop'
};

class Loop
{
    Scope scope;
    int iters;
};

问题是,

class Loop
需要为成员变量定义类
Scope
,而
class Scope
需要定义类
Loop
来构造参数的默认值。 我该如何解决这个问题?另外,我不想让它们中的任何一个嵌套在其他任何一个中。

我之前已经遇到过这个问题,但是可以通过将方法定义移出头文件来忽略它。但是默认参数值必须位于标头中...

c++ class circular-reference
1个回答
0
投票

我想一种解决方案是:

#include <memory>
#include <variant>
#include <vector>

class Scope;

class Command
{
    int code, arg; // whatever
};

class Loop
{
    std::unique_ptr <Scope> scope;
    int iters;
};

using Statement = std::variant<std::monostate, Command, Loop>;

class Scope
{
    std::vector<Statement> statements;
public:
    Statement& appendCmd(const Command& = {});
    Statement& appendLoop(const Loop& = {});
};

但是@RetiredNinja 的评论非常相关。

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