设为首页 加入收藏

TOP

C++11新特性之右值引用(八)
2014-07-19 23:05:03 来源: 作者: 【 】 浏览:386
Tags:特性 引用

 

  方法可以将&&作为参数说明的一部分,从而指定右值引用参数。看例子:

  [cpp] view plaincopyprint

  #include

  using namespace std;

  void showMax(int &a,int &b){

  if(a>b)

  cout<

  else

  cout<

  }

  int main()

  {

  int a=10;

  int b=5;

  showMax(a,b);

  //showMax(20,15); // invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'|

  cin.get();

  return 0;

  }

  发现showMax(20,15)的时候无法正常编译。

  这是因为20,15是一个右值。下面我们定义一个右值引用版本的showMax();

  [cpp] view plaincopyprint

  #include

  using namespace std;

  void showMax(int &a,int &b){

  if(a>b)

  cout<

  else

  cout<

  };

  void showMax(int &&a,int &&b){

  cout<<"这是一个右值引用比较"<

  if(a>b)

  cout<

  else

  cout<

  }

  int main()

  {

  int a=10;

  int b=5;

  showMax(a,b);

  showMax(20,15);

  return 0;

  }

  运行结果:

  当调用showMax(20,15)的时候,编译器将自动调用相对应的右值引用的版本。

  作为方法的参数的时候右值引用非常有用,又例如:

  [cpp] view plaincopyprint

  #include

  using namespace std;

  void show(int &a){

  cout<<"左值引用:"<

  };

  void show(int &&a){

  cout<<"这是一个右值引用:"<

  }

  int main()

  {

        

首页 上一页 5 6 7 8 9 下一页 尾页 8/9/9
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++中如何显式调用构造函数 下一篇C++逆序数与归并排序

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·About - Redis (2025-12-26 08:20:56)
·Redis: A Comprehens (2025-12-26 08:20:53)
·Redis - The Real-ti (2025-12-26 08:20:50)
·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)