包含自身列表的类

时间:2015-08-14 20:49:49

标签: 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*>。我相信提升有我想要的东西,但有没有办法在没有提升的情况下做到这一点?我宁愿使用标准库来了解有关c ++标准库的更多信息。

2 个答案:

答案 0 :(得分:2)

您只需要转发声明class Data,然后在union data正确声明之前声明class 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 ++编译没有问题。

答案 1 :(得分:2)

类成员可能不是不完整的类类型(尽管它们可能是指针或对这些类型的引用)。因此,您需要先定义union data,然后才能在Data中声明此类型的成员。这很简单:

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 {
            int i;
            std::forward_list<Data*> l;
        } actual_data;
        int type;
};

另一个解决方案是首先定义union ,因为它不需要Data类完成,因为它只使用指向它的指针。

union data {
    int i;
    std::forward_list<class 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:
        data actual_data;
        int type;
};
相关问题