【问题标题】:C++17 optional tree, error: invalid use of incomplete typeC++17 可选树,错误:不完整类型的无效使用
【发布时间】:2018-02-04 03:02:08
【问题描述】:

当我编译包含可选类型的二叉树时:

#include <optional>

class BinaryTree
{
public:
    BinaryTree();
    int value;
    std::optional<BinaryTree> left,right;
};

int main()
{
    return 0;
}

通过

g++ -std=c++17 -Wfatal-errors main.cpp 

我遇到了这个错误

In file included from /usr/include/c++/7/bits/move.h:54:0,
                 from /usr/include/c++/7/bits/stl_pair.h:59,
                 from /usr/include/c++/7/utility:70,
                 from /usr/include/c++/7/optional:36,
                 from main.cpp:1:
/usr/include/c++/7/type_traits: In instantiation of ‘struct std::is_trivially_copy_constructible<BinaryTree>’:
/usr/include/c++/7/optional:103:8:   required from ‘class std::_Optional_base<BinaryTree>’
/usr/include/c++/7/optional:451:11:   required from ‘class std::optional<BinaryTree>’
main.cpp:8:28:   required from here
/usr/include/c++/7/type_traits:1409:12: error: invalid use of incomplete type ‘class BinaryTree’
     struct is_trivially_copy_constructible
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated due to -Wfatal-errors.

我应该如何解决这个错误?

【问题讨论】:

  • 如果您不使用std::optional,您将如何声明leftright
  • @DeiDei,我仍然会通过指针声明它们。
  • 编译器需要确定left的大小,这取决于BinaryTree的[完整]定义。本质上,您不能将类的对象嵌入到同一类的对象中。请改用std::unique_ptr&lt;BinaryTree&gt;
  • 你会使用指针,因为BinaryTree 在那个时候仍然是一个不完整的类型。错误是一样的。 std::optional 不是适合这项工作的工具。

标签: c++ templates std optional c++17


【解决方案1】:

Optional 包含该类型在使用时的完整实例。

在一个类型的实例中存储一个类型的两个实例是不可能的;它需要 2

考虑使用指向类型的唯一指针而不是可选的。

如果您希望能够复制树,那么您必须编写一个值指针。值指针是一个知道如何深拷贝自身的指针。

【讨论】:

    【解决方案2】:

    @Yakk 的回答是正确的。

    正如@Dietmar Kühl 指出的那样,std::unique_ptr 是您想要的可空非就地存储:

    #include <memory>
    
    class BinaryTree
    {
    public:
        BinaryTree();
        int value;
        std::unique_ptr<BinaryTree> left,right;
    };
    
    int main()
    {
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      您想使用 BinaryTree 指针而不是实际的 BinaryTree 成员,因为类型不完整。替换

      std::optional<BinaryTree> left,right;
      

      std::optional<BinaryTree*> left,right;
      

      【讨论】:

      • 那么当类型可以为空的时候为什么不BinaryTree* left,right呢?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      相关资源
      最近更新 更多