c++ - 包含自身列表的类

标签 c++ class c++11 standard-library

这就是我想要做的(在我的头文件中):

#include <forward_list>

class Data {
public:
        Data(int type, union data value);
        int which_type();
        void set_int(const int& i);
        void set_list(std::forward_list<Data*>& l);
        int get_int();
        std::forward_list<Data*>* get_list();
private:
        union data actual_data;
        int type;
};

union data {
        int i;
        std::forward_list<Data*> l;
};

如果一切正常,这将创建一个可以包含整数或列表的类,并且它会尽可能的类型安全,因为我会在每次调用 get 函数之一之前调用 which_type 函数,如果对象类型不正确,get 函数将抛出异常。

但是,这是不可能的,因为 Data需要 union data , 和 union data需要 forward_list<Data*> .我相信 boost 有我正在寻找的东西,但是有没有办法在没有 boost 的情况下做到这一点?我宁愿使用标准库来了解有关 c++ 标准库的更多信息。

最佳答案

您只需要前向声明class Data,然后在class Data 正确声明之前声明union data

#include <forward_list>


class Data;
union data {
        int i;
        std::forward_list<Data*> l;
};


class Data {
public:
        Data(int type, union data value);
        int which_type();
        void set_int(const int& i);
        void set_list(std::forward_list<Data*>& l);
        int get_int();
        std::forward_list<Data*>* get_list();
private:
        union data actual_data;
        int type;
};

用 g++ 和 clang++ 编译没有问题。

关于c++ - 包含自身列表的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018440/

相关文章:

c++ - 通过从C++导入图像指针在Lua中处理图像流

c++ - 调用 vector.size() 完成了多少工作?

java - 如何从Android中的其他类而不是Activity调用Activity中的方法?

c++ - 为什么不能使用 initializer_list 来初始化 unique_ptr 的 vector ?

c++ - 使用 QSimpleXmlNodeModel 和 QTreeView

c++ - GMock,调用 SaveArg 捕获的 std::function

javascript - 从类方法中使用jquery悬停

PHP 使用 $this->variable 作为类方法参数默认值

c++11 - 为什么 C++11 std::array 是结构而不是类?

c++ - 锁定多个 std::mutex 的最佳方法是什么?