为什么nullptr无法转换为int? [英] Why can't nullptr convert to int?

查看:110
本文介绍了为什么nullptr无法转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘要: nullptr 转换为 bool ,而 bool 转换为 int ,为什么不 nullptr 转换为 int 吗?

Summary: nullptr converts to bool, and bool converts to int, so why doesn't nullptr convert to int?

此代码还可以:

void f(bool);
f(nullptr);      // fine, nullptr converts to bool

这没关系:

bool b;
int i(b);        // fine, bool converts to int

那为什么不行呢?

void f(int);
f(nullptr);      // why not convert nullptr to bool, then bool to int?

推荐答案

因为它正是 nullptr 的主要思想.

Because it is exactly the main idea of nullptr.

nullptr 旨在避免此行为:

struct myclass {};

void f(myclass* a) { std::cout << "myclass\n"; }
void f(int a) { std::cout << "int\n"; }

// ...

f(NULL); // calls void f(int)

如果 nullptr 可转换为 int ,则会发生此行为.

If nullptr were convertible to int this behavior would occur.

所以问题是"为什么可以转换为 bool ?".

语法-建议":

int* a = nullptr;
if (a) {
}

看起来比以下更好:

if (a == nullptr) {
}

这篇关于为什么nullptr无法转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆