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

c – 对const字符串引用的隐式转换失败

发布时间:2020-12-16 09:53:34 所属栏目:百科 来源:网络整理
导读:为什么将Foo和Bar的函数参数从const更改为非const导致不同的编译器错误? 或者换句话说:为什么Foo(false)ok,而Bar(false)导致编译器错误? #include stringvoid Foo(const std::string test){}void Bar(std::string test){}int main(int,char* []){ Foo(fal
为什么将Foo和Bar的函数参数从const更改为非const导致不同的编译器错误?
或者换句话说:为什么Foo(false)ok,而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版本的引用无法做同样的事情,因为临时对象不是左值.

(编辑:李大同)

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

    推荐文章
      热点阅读