传递对引用的引用

编程入门 行业动态 更新时间:2024-10-23 19:28:24
本文介绍了传递对引用的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我认为在 C++ 中传递对引用的引用是非法的.但是,当我运行此代码时,它没有给我任何错误.

I think it's illegal to pass a reference to a reference in C++.However ,when I run this code it gives me no error.

void g(int& y) { std::cout << y; y++; } void f(int& x) { g(x); } int main() { int a = 34; f(a); return 0; }

是不是形式参数G()有资格作为对参考的参考 ??

Doesn't the formal parameter of g() qualify as a reference to a reference ??

推荐答案

1) 将引用传递给引用并没有错(它是移动构造函数和移动赋值运算符使用的 - 尽管它实际上被称为右值引用).

1) There is nothing wrong with passing a reference to a reference (it is what the move-constructor and move-assignment operators use - though it is actually called a rvalue-reference).

2) 你所做的不是将引用传递给引用,而是将相同的引用通过 f 传递给 g:

2) What you are doing is not passing a reference to a reference, but rather passing the same reference through f to g:

void g(int& x) { x = 5; } void f(int& x) { std::cout << "f-in " << x << std::endl; g(x); std::cout << "f-out " << x << std::endl; } int main() { int x = 42; f(x); std::cout << "New x = " << x << std::endl; }

更多推荐

传递对引用的引用

本文发布于:2023-11-12 20:36:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582471.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!