【问题标题】:Class that contains a list of itself包含自身列表的类
【发布时间】:2015-11-08 04:54:12
【问题描述】:

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

#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&lt;Data*&gt;。我相信 boost 有我正在寻找的东西,但是有没有办法在没有 boost 的情况下做到这一点?我宁愿使用标准库来了解更多关于 c++ 标准库的信息。

【问题讨论】:

  • 为什么不转发声明Data并将union_data移到Data的定义之前?

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


【解决方案1】:

您只需要转发声明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++ 可以做到这一点。谢谢。
【解决方案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;
};

另一个解决方案是首先定义联合,因为它不需要完整的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;
};

【讨论】:

  • 这个不行,我试过了。它确实需要数据,即使它只是一个指针。
  • 我现在遇到了各种其他错误,所以我会在解决这些问题后通知您。
  • 好的,当我尝试你的第二个建议时(第一个可能有效,但我没有尝试过),我收到一个错误:error: 'Data' was not declared in this scope std::forward_list&lt;Data*&gt;* l;
  • 实际上,我现在看到了您和我的代码之间的区别。我在联合定义中使用了Data* 而不是class Data*。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多