如何使用特定类型创建 NULL

How to create NULL with certain type?

本文关键字:创建 NULL 类型 何使用      更新时间:2023-10-16

我的代码是

TreeNode *sortedArrayToBST(vector<int> &num) {
    function<TreeNode*(int,int)> func=
        [&func,&num](int s, int e){
            TreeNode* p = NULL;
            if(s>e) return NULL; // change to return p would compile
            int m = (s+e)/2;
            p = new TreeNode(num[m]);
            p->left = func(s,m-1);
            p->right = func(m+1,e);
            return p;
        };
    return func(0,num.size()-1);
}
Solutions.cpp:957:21: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]
Solutions.cpp:959:29: error: inconsistent types ‘TreeNode*’ and ‘int’ deduced for lambda return type
Solutions.cpp:959:29: error: invalid conversion from ‘TreeNode*’ to ‘int’ [-fpermissive]
Solutions.cpp:962:12: error: inconsistent types ‘TreeNode*’ and ‘int’ deduced for lambda return type
Solutions.cpp:962:12: error: invalid conversion from ‘TreeNode*’ to ‘int’ [-fpermissive]

我通过创建 TreeNode* 类型的 NULL 来修复代码。我的问题是如何创建一个带有类型的 NULL,这样我就不需要仅仅为了返回 NULL 指针而声明一个临时变量。像NULL(TreeNode)这样的东西;

使用:

function<TreeNode*(int,int)> func=
    [&func,&num](int s, int e) -> TreeNode* /*explicitly define return type*/ {
        //nullptr is beter than NULL with C++11
        TreeNode* p = nullptr;
        if(s>e) return nullptr; // we return nullptr here
        int m = (s+e)/2;
        p = new TreeNode(num[m]);
        p->left = func(s,m-1);
        p->right = func(m+1,e);
        return p;
    };

请参阅 http://www.stroustrup.com/C++11FAQ.html#nullptr(有关 nullptr 的一些信息)

为什么会出现编译器错误

NULL 实际上是一个整数,当编译器尝试确定 lambda 的返回类型时,这会导致一些混淆(当您编写返回 NULL 时返回一个整数,稍后您还有一个返回 p(这是一个 TreeNode*)。所以编译器不知道它应该为 lambda 的返回类型推导出什么类型(它是 int 还是指向 TreeNode 的指针)?

您可以消除显式声明返回类型的歧义并使用 nullptr(只是因为这是您在 C++11 中应该这样做的方式)。

这是

c++11,你应该使用 nullptr,NULL 基本上已经过时了,null 也没有类型,它只是 0(通常)。你的代码错误,因为 NULL 基本上只是一个 int(它是 0) 在这个游戏中返回nullptr也可能不起作用,因为它具有nullptr_t类型。

编辑:我检查了,不幸的是,我最初的想法是正确的,nullptr有一个nullptr_t类型,因此您可以显式指定返回类型。 有了[...](...)->TreeNode*{...},然后一切应该都正常