为什么更改fromFoo
和Bar
from的功能参数const
会non-const
导致不同的编译器错误?
或者换句话说:为什么Foo(false)
还可以,而Bar(false)
导致编译器错误?
#include <string>
void Foo(const std::string &test)
{
}
void Bar(std::string &test)
{
}
int main(int , char* [])
{
Foo(false);
Bar(false); // error C2664: 'Bar' : cannot convert parameter 1 from 'bool' to 'std::string &'
return 0;
}
当您使用bool
参数调用函数时,编译器将寻求从可行的转换bool
为参数具有的任何类型:const std::string &
在第一种情况下,std::string &
在第二种情况下。
std::string
是可从构造的const char *
,后者false
为整数常量0,可隐式转换为(将导致nullptr
)。因此,将构造一个临时字符串并将其绑定到const引用。
对于引用的非const版本,无法完成相同的操作,因为临时对象不是左值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句