关于运算符重载的问题
我试图理解一个程序,其中包含函数 f 的以下定义,
void f(String S, const String& r)
{
}
这里参数中的字符串代表一个类。我对这两个参数的定义之间的差异感到困惑:“String S”和“const String& r”。 S应该代表String类的对象,那么r呢?
更详细地说,f 被定义为
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'
}
此代码片段是为了展示运算符如何重载,但这些注释对我没有多大帮助。例如,为什么 r[1]='d' 不正确?感谢您帮助理解它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
const String& r
是对字符串 r 的常量引用。在函数中,您可以像访问字符串一样访问r
。不同之处在于,它实际上是对传递给函数的对象的引用,而S
将是传递给函数的对象的副本。您几乎可以将其视为通过取消引用的指针访问r
(尽管还有更多内容)。另一种看待它的方式:调用者将看到
r
的更改(如果它不是const
),而他不会看到S
的更改代码>.const
只是意味着函数f
不能修改r
。另请参阅:https://isocpp.org/wiki/faq/references#overview-refs< /a>
const String& r
is a constant reference to String r. Within the function, you accessr
just like a String. The difference is that it is actually a reference to the object passed to the function, whileS
will be a copy of the object passed to the function. You can almost think of it as if you are accessingr
through 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
const
simply means the functionf
cannot modifyr
.See also: https://isocpp.org/wiki/faq/references#overview-refs
这似乎只是一个例子,来展示传递参数的方式之间的差异。
您可能会按值传递一个参数的一种实际情况是您无论如何都需要该值的副本。也许在连接两个字符串时。
This seems to be just an example, to show the difference between ways of passing parameters.
One real case where you might pass one parameter by value, is when you need a copy of the value anyway. Perhaps when concatenating the two strings.