如何使用特定类型创建 NULL
How to create NULL with certain type?
我的代码是
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*{...}
,然后一切应该都正常
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- C++ - 创建具有相同字符的特定大小的以 null 结尾的 c 样式字符串的更好方法
- 为 C 绑定创建动态以 null 结尾的参数
- 使用new创建指针数组,这样指针就不会初始化为NULL
- 如何使用 **P 创建一个指针数组并将其指向 NULL
- 如何使用特定类型创建 NULL
- 如何确保最近创建的区域指向 NULL
- C++:是否可以创建返回null的模板函数
- CreateWindowEx返回null:无法创建窗口
- 在构造函数中创建hbitmap返回NULL
- std::thread::id 默认构造函数不应该创建一个"NULL" id吗?
- 为动态创建的TComponent派生类实例传递一个NULL Owner参数OK
- 如何在创建新结构体时给成员指针赋NULL值
- 为什么使用 'new' 创建的数组设置为 NULL?
- 如何声明一个函数,该函数创建一个永远不会为 null 的对象
- 创建时SDL_renderer变为 null