加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么在C中有指针到bool的隐式类型转换?

发布时间:2020-12-16 05:35:22 所属栏目:百科 来源:网络整理
导读:考虑类foo与两个这样定义的构造函数: 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;}}; 用字符串文字实例化类,并猜测哪个构造函数被调用? foo a
考虑类foo与两个这样定义的构造函数:
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;}
};

用字符串文字实例化类,并猜测哪个构造函数被调用?

foo a ("/path/to/file");

输出:

ctor 2

我不知道你,但我没有发现编程历史上最直观的行为.我敢打赌,有一些聪明的理由,但是,我想知道这可能是什么?

解决方法

在C写这个很常见
void f(T* ptr) {
    if (ptr) {
        // ptr is not NULL
    }
}

你应该使一个const char *构造函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读