QifengSun
QifengSun

Reputation: 33

how to passing a argument to this parameter?

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&);

Upvotes: 1

Views: 1862

Answers (2)

Ari0nhh
Ari0nhh

Reputation: 5930

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:

  1. return a std::string from your function:

    string PalindromeFinder::truncateToLargestPalindrome(const string& inputString)
    

    cout << truncateToLargestPalindrome("djfklsevesdfjkf") << endl;
    
  2. 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;
    

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 598414

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;

Upvotes: 2

Related Questions