代码之家  ›  专栏  ›  技术社区  ›  Oystein

为什么C++中指针从BoL到隐式类型转换?

  •  14
  • Oystein  · 技术社区  · 15 年前

    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");
    

    输出:

    我不知道你的情况,但我不认为这是编程史上最直观的行为。不过,我敢打赌这是有原因的,我想知道那可能是什么?

    3 回复  |  直到 15 年前
        1
  •  12
  •   Lou Franco    15 年前

    在C语言中,写这个是很常见的

    void f(T* ptr) {
        if (ptr) {
            // ptr is not NULL
        }
    }
    

    const char* 构造器。

        2
  •  4
  •   asdfjklqwer    15 年前

        3
  •  0
  •   wheaties    15 年前

    你混淆了两个问题。一个是 "blah" 可以隐式转换为 string 另一个是 const char*

    推荐文章