如何用某种类型创建NULL?

时间:2013-09-25 19:29:45

标签: c++ c++11 g++

我的代码是

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);

2 个答案:

答案 0 :(得分: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;
    };

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

为什么会出现编译错误

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

您可以明确指出显式返回类型并使用nullptr(因为这是您应该如何在C ++ 11中执行此操作)。

答案 1 :(得分:2)

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

编辑:我检查过,不幸的是,我原来的想法是正确的,nullptrnullptr_t类型,因此您可以明确指定返回类型。使用[...](...)->TreeNode*{...}然后一切都应该正常工作