函数的返回类型

返回指针类型:

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

代码:

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 : \n";
    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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值