string version1(const string & s1, const string & s2)
{
string temp;
temp = s2 + s1 + s2;
return temp;
}
string input;
getline(cin, input);
result = version1(input, "***");
Now the question is, how can it be that the string literal "***" can be passed as it is a string object to the function version1?
The answer has two parts:
1. The string class defines a char * to string conversion.
2. If a actual argument does not match the const reference argument, and the argument can be converted to the correct type, then a temporary variable of the correct type is created, a string in this case, and is used during the existence of the function called.
Earlier you saw that a const double & parameter can handle an int argument in this fashion.
The convenient outcome of this is that if the formal parameter is type const string &, the actual argument used in the function call can be a string object or a C-style string, such as a quoted string literal, a null-terminated array of char, or a pointer variable that points to a char.
Hence, the following works fine:
result = version1(input, "***");
Abonneren op:
Reacties posten (Atom)
Geen opmerkingen:
Een reactie posten