关于函数返回值为引用和指针的问题
如果函数的返回值为引用,则不需要创建无名临时对象,避免构造函数和析构函数的调用,从空间和时间上提高了程序执行的效率 返回值为引用的情况。 #include<iostream> #include<string> using namespace std; char & get_value(string &str,int i) { return str[i]; } int main() { char str[]="abcdef"; get_value(str,2)="h"; //返回str中c字符变量,重新给变量复制为h. return 0; } 没有引用的情况: #include<iostream> #include<string> using namespace std; char get_value(string &str,int i) { return str[i]; } int main() { char str[]="abcdef"; char p; p= get_value(str,2) ; cout<<p<<endl; return 0; } 返回值类型没有引用时,返回的是一个无名的临时变量,其值为返回内容的一份临时的拷贝。 返回值类型为引用的情况一般用于输入输出流重载函数,可以实现连续输入和输出。 代码如下: #include<iostream> using namespace std; ostream & operator<<(ostream &out,Complex &c) { out<<"("<<c.real<<"+"<<c.imag<<")"<<endl; return out; } 对于指针一般不返回局部变量的指针,除了局部域指针会失效,一般返回全局变量的指针。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。