error: invalid initialization of non-const reference of type ‘std::__cxx11::string& {aka std::__c…

内容分享2个月前发布
0 0 0

C++ 错误排查,代码用来实现string头尾调换, the call of reverse(“Hi you!”) should return “!uoy iH” ,用递归实现

#include <iostream>

using namespace std;

string reverse(string &s) {

    if (s == “”) return “”;

    return reverse(s.substr(1)) + s[0];

}

int main() {

    string s = “Hi you!”;

    string r = reverse(s);

    cout << r << endl;

    return 0;

}

error: invalid initialization of non-const reference of type std::__cxx11::string& {aka std::__cxx11::basic_string<char>&} from an rvalue of type std::__cxx11::basic_string<char> return reverse(s.substr(1)) + s[0];

这里的reverse不能被递归调用,

缘由: a reference to non-const cannot be bound to a temporary object (aka r-value)

s.substr(1) creates a temporary object (aka rvalue) cannot be bound to a reference to non-const,

so How come a non-const reference cannot bind to a temporary object?

看StackOverflow这篇,

https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object

SO

Use Reference to const whenever Possible

© 版权声明

相关文章

暂无评论

none
暂无评论...