如何用某种类型创建NULL?

use*_*129 3 c++ g++ c++11

我的代码是

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]
Run Code Online (Sandbox Code Playgroud)

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

ds2*_*680 6

使用:

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;
    };
Run Code Online (Sandbox Code Playgroud)

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

为什么会出现编译错误

NULL实际上是一个整数,这会在编译器尝试确定lambda的返回类型时引起一些混淆(当你写回返NULL时返回一个整数,然后在行下面返回一个返回p(这是一个TreeNode*))那么编译器不知道它应该为lambda的返回类型推导出什么类型(是int还是指向TreeNode的指针)?

您可以明确说明返回类型的歧义并使用nullptr(因为这是您应该在C++ 11中执行此操作的方式).