gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:44:55 26 4
gpt4 key购买 nike

考虑以下代码:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com