I defined a function at here
void PalindromeFinder::truncateToLargestPalindrome(string& inputString)
and when I want to test this function I use
cout<<truncateToLargestPalindrome("djfklsevesdfjkf")<<endl;
then the compiler gave me this error
PalindromeFinder.cpp:19:36: error: non-const lvalue reference to type 'string'
(aka 'basic_string<char, char_traits<char>, allocator<char> >') cannot
bind to a value of unrelated type 'const char [8]'
cout<<truncateToLargestPalindrome("racecar")<<endl;
^~~~~~~~~
./PalindromeFinder.h:22:45: note: passing argument to parameter here
void truncateToLargestPalindrome(string&);
If you want to pass the result of your function to the <<
operator, the function has to actually return something. In your current implementation, it returns nothing ( void
), so your code is clearly incorrect.
To make it work, you have to either:
return a std::string
from your function:
string PalindromeFinder::truncateToLargestPalindrome(const string& inputString)
cout << truncateToLargestPalindrome("djfklsevesdfjkf") << endl;
call the function first to modify a local variable, and then stream that variable to cout
:
std::string str = "djfklsevesdfjkf"; truncateToLargestPalindrome(str); cout << str << endl;
You cannot pass a string literal to a non-const string&
parameter. The compiler would need to create a temporary string
object, but a temporary cannot bind to a non-const lvalue reference , only to a const lvalue reference or an rvalue reference . Thus the compiler error.
You need to change the parameter to be a const
reference so a temporary string
can bind to it. Then you can pass string literals to it.
Also, your function is not returning anything, so you cannot pass it to a streaming <<
operator (or any other operator, for that matter).
Try this instead:
string PalindromeFinder::truncateToLargestPalindrome(const string& inputString)
{
string outputString = inputString;
// modify outputString as needed...
return outputString;
}
cout << truncateToLargestPalindrome("djfklsevesdfjkf") << endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.