临时对象只能用常量引用绑定,这时在常量引用上只能调用常量函数。
但是可以直接在临时对象上调用成员函数(若存在非常量函数和常量函数,优先调用非常量函数)。
- #include <stdio.h>
- #include <iostream>
- using namespace std;
- class A{
- public:
- virtual void func(int data){printf("A1 :%d/n",data);}
- virtual void func(int data) const {printf("A2 :%d/n",data);}
- };
- void func(const A &t)
- {
- t.func(10);
- cout<<" func is called!"<<endl;
- }
- A test()
- {
- return A();
- }
- int main()
- {
- //A& a = A(); //error ,A()返回临时对象,只能用常量引用绑定
- const A &a = A(); //seccessful
- a.func(20); //调用常量函数
- func(A());
- A().func(1);//调用非常量函数(若存在)
- test().func(100);//调用非常量函数(若存在)
- return 0;
- }