I am trying to understand a program, which includes the following definition for a function f
void f(String S, const String& r)
{
}
Here String in the argument stands for a class. I am confused on the difference between the definitions of these two arguments: “String S” and “const String& r”. S should represent an object of class String, then how about r?
In more detail, the f is defined as
void f(String S, const String& r)
{
int c1 = S[1]; // c1=s.operator[](1).operator char( )
s[1] ='c'; // s.operator[](1).operator=('c')
int c2 = r[1]; // c2 = r.operator[](1)
r[1] = 'd'; // error: assignment to char, r.operator[](1) = 'd'
}
This code snippet is to show how the operator overload, but these comments does not help me much. For instance, why r[1]=’d’ is nor correct? Thanks for helping understanding it.
const String& ris a constant reference to String r. Within the function, you accessrjust like a String. The difference is that it is actually a reference to the object passed to the function, whileSwill be a copy of the object passed to the function. You can almost think of it as if you are accessingrthrough a de-referenced pointer (though there is more to it than that).Another way to look at it: The caller will see changes to
r(if it wasn’tconst), while he will not see changes toS.The
constsimply means the functionfcannot modifyr.See also: https://isocpp.org/wiki/faq/references#overview-refs