传递对引用的引用 [英] Pass a reference to a reference

查看:61
本文介绍了传递对引用的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为在 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;
}

这篇关于传递对引用的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆