临时对象的引用绑定
2008-08-03 18:05
176 查看
临时对象只能用常量引用绑定,这时在常量引用上只能调用常量函数。
但是可以直接在临时对象上调用成员函数(若存在非常量函数和常量函数,优先调用非常量函数)。
#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;
}
但是可以直接在临时对象上调用成员函数(若存在非常量函数和常量函数,优先调用非常量函数)。
#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;
}
相关文章推荐
- 非const引用参数传入不同类型编译不过的理解(拒绝将临时对象绑定为非const的引用的形参是有道理的)
- 由重建二叉树算法题到临时对象不能绑定到非 const 的左值引用
- [转帖]无法将临时对象绑定到非常量引用
- 临时对象不能被绑定到非const引用参数上====》扩展到临时对象问题
- 关于临时对象的引用
- C++非const的引用不能指向临时对象
- 非常量引用不能绑定在临时变量上
- C++产生的临时对象引用
- C++标准的规定:非常量的引用不能指向临时对象
- c++ 非常量引用产生临时对象
- 第二十二节:类与对象-后期静态绑定-对象和引用
- datagrid中DropDownList绑定Dataset 的探究 未将对象引用设置到对象的实例 错误
- Gotchas 44-引用和临时对象
- 引用参数与引用返回值,临时对象
- C++中的临时对象,对临时对象的引用,和临时对象的指针
- 引用初始化(临时对象)
- 非常量引用不能绑定在临时变量上
- C++标准的规定:非常量的引用不能指向临时对象(转载)
- 函数返回的临时对象为const类型,const引用
- C++中的临时对象,对临时对象的引用,和临时对象的指针