c++ - C++ 中的默认参数不匹配?

标签 c++ type-conversion default-parameters

考虑以下代码:

#include <iostream>

class Bar
{
public:
    void foo(bool b = false, std::string name = "");
};

void Bar::foo(bool b, std::string name)
{
    if (!b)
    {
       std::cout << "b is false" << std::endl;
    }
    else
    {
       std::cout << "b is true" << std::endl;
    }
}

int main()
{
    Bar myBar;
    myBar.foo("bla");
    return 0;
}

我猜 C++ 没有损坏,但是有人可以解释为什么输出是真的吗?我正在使用 VS 2010,但我也检查了运行 gcc 的 ideone

最佳答案

编译器隐式转换第一个参数,一个 char const[4] , 至 bool , 结果为 true .

相当于

myBar.foo((bool)"bla");

也等同于

myBar.foo((bool)"bla", "");

关于c++ - C++ 中的默认参数不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11982470/

相关文章:

c# - C# 上不允许出现默认参数说明符错误

c++ - 具有依赖于早期参数的默认模板参数是否有效?

c++ - Meyers 实现的 Singleton 模式线程安全吗?

c++ - Boost线程开销

java - 如何在 Java 中将整数字符串转换为 ArrayList?

c - 将一个数字放入数组中,并将其从 char 转换为 int

c++ - 默认参数和可变参数函数

python - Boost.Python boost::shared_ptr 没有通过值转换器找到 python

c++ - 从 C++ 中的类构造函数调用头文件中定义的函数

javascript - 在javascript中添加两个空白对象或空白数组