Why is there an implicit type conversion from pointers to bool in C++?(为什么在 C++ 中存在从指针到 bool 的隐式类型转换?)
问题描述
考虑类 foo 有两个这样定义的构造函数:
Consider the class foo with two constructors defined like this:
class foo
{
public:
foo(const std::string& filename) {std::cout << "ctor 1" << std::endl;}
foo(const bool some_flag = false) {std::cout << "ctor 2" << std::endl;}
};
用字符串字面量实例化类,猜猜调用的是哪个构造函数?
Instantiate the class with a string literal, and guess which constructor is called?
foo a ("/path/to/file");
输出:
构造函数 2
我不了解您,但我不认为这是编程史上最直观的行为.不过,我敢打赌它有一些巧妙的理由,我想知道那可能是什么?
I don't know about you, but I don't find that the most intuitive behavior in programming history. I bet there is some clever reason for it, though, and I'd like to know what that might be?
推荐答案
在 C 中写这个很常见
It's very common in C to write this
void f(T* ptr) {
if (ptr) {
// ptr is not NULL
}
}
你应该创建一个 const char* 构造函数.
You should make a const char* constructor.
这篇关于为什么在 C++ 中存在从指针到 bool 的隐式类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 C++ 中存在从指针到 bool 的隐式类型转换?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
