从函数返回引用确保其引用的对象在函数执行完后仍然存在。
引用类型返回值的主要特征是可以作为左值,这意味着我们可以在赋值语句的左边使用返回引用的函数的结果。
永远不要从函数中返回局部变量的引用.
(1)首先,返回引用,要求在函数的参数中,包含有以引用方式或指针方式存在的,需要被返回的参数。比如:
int& abc(int a, int b, int c, int& result){
result = a + b + c;
return result;
}
这种形式也可改写为:
int& abc(int a, int b, int c, int *result){
*result = a + b + c;
return *result;
}
但是,如下的形式是不可以的:
int& abc(int a, int b, int c){
return a + b + c;
}
众所周知,C++函数可以传入引用参数和返回引用。
int& abc(int a, int b, int c, int& result){
result = a + b + c;
return result;
}
这种形式也可改写为:
int& abc(int a, int b, int c, int *result){
*result = a + b + c;
return *result;
}
但是,如下的形式是不可以的:
int& abc(int a, int b, int c){
return a + b + c;
}
众所周知,C++函数可以传入引用参数和返回引用。
函数引用参数避免了过多的指针操作,对加强函数的可读性很有帮助;另外,在传入体积很大的类型的变量时,引用参数可以避免拷贝对象,加快程序运行效率。
函数支持引用型的返回值是为什么呢?这个问题要一分为二:对于类类型的引用返回值,函数可以在使用重载运算符的串联表达式中使用,而不用担心构造多个对象。
#include <stdio.h>
#include <iostream>
using namespace std;
class Rec
{
public:
int a;
int b;
friend ostream & operator<<(ostream &os,Rec& b)
{
os<<"["<<b.a<<"]";
return os;
}
};
Rec & funRec(Rec& obj)
{
return obj;
}
int main(int argc , char* args[])
{
Rec obj;
Rec *ptr = &(funRec(obj));
Rec ano = funRec(obj);
printf("&obj = %p/nptr = %p/n&ano = %p/n", &obj, ptr, &ano);
return 0;
}
#include <iostream>
using namespace std;
class Rec
{
public:
int a;
int b;
friend ostream & operator<<(ostream &os,Rec& b)
{
os<<"["<<b.a<<"]";
return os;
}
};
Rec & funRec(Rec& obj)
{
return obj;
}
int main(int argc , char* args[])
{
Rec obj;
Rec *ptr = &(funRec(obj));
Rec ano = funRec(obj);
printf("&obj = %p/nptr = %p/n&ano = %p/n", &obj, ptr, &ano);
return 0;
}
运行结果:
&obj = 0xbf90e338
ptr = 0xbf90e338
&ano = 0xbf90e330
可见,红色代码只会生成一个对象,绿色代码部分需要调用拷贝构造函数。因为fucRec传入引用参数,返回引用对象。如果返回的不是引用对象,那么在语句Rec *ptr = &( funRec(obj) );编译不过。
ptr = 0xbf90e338
&ano = 0xbf90e330
可见,红色代码只会生成一个对象,绿色代码部分需要调用拷贝构造函数。因为fucRec传入引用参数,返回引用对象。如果返回的不是引用对象,那么在语句Rec *ptr = &( funRec(obj) );编译不过。
本文深入探讨C++中引用的使用技巧,包括如何正确地从函数返回引用,避免返回局部变量的引用,以及引用作为函数参数的优势。通过实例展示引用如何提高代码效率。
206

被折叠的 条评论
为什么被折叠?



