C++函数取值,而它们应该取引用
我刚刚学习 c++,来自 c,我在书中看到的一些函数调用让我感到困惑:
char a;
cin.get(a);
在 C 中,这不可能工作,如果你这样做,将无法获得输出,因为你是按值传递,而不是按引用传递,为什么这在 C++ 中有效?引用和取消引用是否是隐式的(编译器知道 cin.get 需要一个指针,因此它被引用)?
I'm just learning c++, and coming from c, some function calls I'm seeing in the book confuse me:
char a;
cin.get(a);
In C, this couldn't possibly work, if you did that, there would be no way to get the output, because you are passing by value, and not by reference, why does this work in c++? Is referencing and dereferncing made implicit (the compiler knows that cin.get needs a pointer, so it is referenced)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++
这在 C++ 中是可行的,因为
get()
的函数签名可能是这样的:char
后面的&
符号code> 向编译器表示,当您传入char
值时,它应该传入对char
的引用,而不是制作副本它的。这本质上意味着在
get()
内所做的任何更改都将反映在方法外部a
的值中。如果
get()
的函数签名是这样的:那么
a
将通过 value 传递,这意味着a< 的副本/code> 在作为参数传递到方法之前创建。对
a
的任何更改都将仅是方法的本地更改,并在方法返回时丢失。C
这在 C 中不起作用的原因是因为 C 只有按值传递。在 C 中模拟“按引用传递”行为的唯一方法是按值传递其指针,然后在修改指针值时取消引用该指针值(从而访问相同的内存位置)方法:
运行该程序将输出:
C++
This would work in C++ because the function signature for
get()
is probably this:The
&
symbol afterchar
denotes to the compiler than when you pass in achar
value, it should pass in a reference to thechar
rather than making a copy of it.What this essentially means is that any changes made within
get()
will be reflected in the value ofa
outside the method.If the function signature for
get()
was this:then
a
would be passed by value, which means a copy ofa
is made before being passed into the method as a parameter. Any changes toa
would then only be local the method, and lost when the method returns.C
The reason why this wouldn't work in C is because C only has pass-by-value. The only way to emulate pass-by-reference behaviour in C is to pass its pointer by value, and then de-reference the pointer value (thus accessing the same memory location) when modifying the value within the method:
Running this program will output:
引用类型的工作方式与此类似(通过引用传递,而不是通过值传递)。它类似于 C 中的传递指针(pass by point),但具有更好的语法和更高的安全性(编译时检查)。实现在内部通过指针传递。
Reference types work like that (pass by reference, instead of passing by value). It is similar to passing a pointer (pass by pointer) in C, but with a nicer syntax and more safety (compile-time checks). The implementation passes by pointer internally.
C++ 允许按引用传递(请注意
&
,它表示使用了引用):C++ allows pass by reference (note the
&
, which signifies that a reference is used):这就是为什么一些 C++ 程序员不喜欢使用这样的引用。
它看起来像一个函数争论 - 从语法中你不知道 'a' 是否被修改。
更喜欢传递常量引用(当您有一个大对象并且副本会很昂贵时)并返回引用或最好的传递指针。
This is why some C++ programmers don't like to use references like that.
It looks like a function arguement - you have no clue from the syntax whether 'a' is modified or not.
Prefer passing const references (when you have a large object and a copy would be expensive) and returning references or best of all passing pointers.