Hi,
How do I properly put this to code? I am trying to return a string (name) from a function using reference.
I hope you get the idea. Thanks!Code:std::string& name() { cout << "Enter your name: " << endl; getline(cin, name); }
Hi,
How do I properly put this to code? I am trying to return a string (name) from a function using reference.
I hope you get the idea. Thanks!Code:std::string& name() { cout << "Enter your name: " << endl; getline(cin, name); }
You need to pass in the string by reference, but you probably should either rename the function or use a different name for the string reference parameter. Of course, once you pass in the string by reference, there is not much point in returning it at all.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I think there are some cases that benefit from returning a reference. For example, I have a function to convert something to a string, and use the converted string in a string expression. I can pass in a string reference, store the converted string in it, and return a reference to it. This way, I can avoid a string copy operation. Here is some abstract code to explain what I mean:
Code:string & int2str(int i, string & str){ // convert i into str return str; } int main(){ ... string tmp; string a = "abc" + int2str(20, tmp); ... }
Yes, but I do not think that this is one of them.Originally Posted by plutino
Depending on your point of view, you either cannot avoid the copy (since you are initialising a new string with a temporary) or can avoid the copy either way, e.g.,Originally Posted by plutino
Code:string tmp; int2str(20, tmp); string a = "abc" + tmp;
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)