函数的返回类型

返回指针类型:

函数原型为 : 类型 * 函数名(形参列表);

代码:

include<iostream>
using namespace std;
int *max(int *, int *);
int main()
{
int a, b;
cout << "please input a and b:" << endl;
cin >> a >> b;
cout << "the maximun of a and b is " << *max(&a, &b) << endl;  //此处的*max(&a,&b)表示,先调用。数返回a和b的中较大的变量的地址,再用*进行访问
system("pause");
}
int *max(int *x, int *y)     //接收指针类型做参数
{
if (*x > *y)   
{
return x;         //返回指针
}
return y;
}

返回引用类型:
c++函数返回引用类型时,不需创建临时变量来存储返回值。

代码:

#include<iostream>
#include<cstring>
using namespace std;
int a, b;
int & count(int);
int main()
{
    int x;
    cout << "Input numbers,the 0 is end : 
";
    cin >> x;
    while (x)
    {
        count(x)++;
        cin >> x;
    }
    cout << "the number of right: " << a << endl;
    cout << "the number of negative: " << b << endl;
    system("pause");
}
int & count(int n)
{
    if (n > 0)
    {
        return a;
    }
    return b;
}

分析:在此代码中,由于a,b在main()函数前声明,所以是全局变量,对整个代码可见,所以count函数可以返回a和b的引用。在main函数中,因为count函数返回的是引用,相当于返回了变量a或者b的别名,所以可用对其返回值进行修改,也就是返回引用的函数调用可以作为左值。

原文地址:https://www.cnblogs.com/urahyou/p/10022085.html