临时对象的引用绑定

来源:互联网 发布:网络文明ppt免费下载 编辑:程序博客网 时间:2024/05/02 04:44

临时对象只能用常量引用绑定,这时在常量引用上只能调用常量函数。

但是可以直接在临时对象上调用成员函数(若存在非常量函数和常量函数,优先调用非常量函数)。

  1. #include <stdio.h>
  2. #include <iostream>
  3. using namespace std;
  4. class A{
  5. public:
  6.     virtual void func(int data){printf("A1 :%d/n",data);}
  7.     virtual void func(int data) const {printf("A2 :%d/n",data);}
  8. };
  9. void func(const A &t)
  10. {
  11.     t.func(10);
  12.     cout<<" func is called!"<<endl;
  13. }
  14. A test()
  15. {
  16.     return A();
  17. }
  18. int main()
  19. {
  20.     //A& a = A(); //error ,A()返回临时对象,只能用常量引用绑定
  21.     const A &a = A(); //seccessful
  22.     a.func(20); //调用常量函数
  23.     func(A());
  24.     A().func(1);//调用非常量函数(若存在)
  25.     test().func(100);//调用非常量函数(若存在)
  26.     return 0;
  27. }
原创粉丝点击