gpt4 book ai didi

c++ - 将 NULL 转换为 long 是不是有歧义?

转载 作者:可可西里 更新时间:2023-11-01 18:10:04 24 4
gpt4 key购买 nike

我正在尝试使用 NULL 与 nullptr 的示例。由于 NULL 可以转换为整数类型,因此它应该与下面的示例显示出歧义,但事实并非如此!

它显示不明确的候选编译错误,如果它是 unsigned long,但不是 signed long。

谁能解释一下原因!!

#include <iostream>
using namespace std;

// NOTE:
// "long" or "signed long" is not showing ambiguous candidates
// but "unsigned long" does

void func(long st) {
cout << "overload func\n";
}

void func(int* ptr) {
cout << "integer pointer overload func\n";
}

int main() {
func(NULL);
return 0;
}

最佳答案

在C++中,NULL被定义为整型。您的编译器可能将其定义为 long,因为它匹配该重载。 C++ 标准明确规定(草案 N3936,第 444 页):

Possible definitions [of macro NULL] include 0 and 0L, but not (void*)0.

这个限制是必要的,因为例如char *p = (void*)0 在 C 中有效但在 C++ 中无效,而 char *p = 0 在两者中均有效。

关于c++ - 将 NULL 转换为 long 是不是有歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com