函数返回问题

[复制链接]
 楼主| xsgy123 发表于 2013-6-29 21:43 | 显示全部楼层 |阅读模式
如下代码:
#include <iostream>
using namespace std;

class CStudent
{
public:
    static int noOfStudents;
    CStudent& nextStudent()
    {
        noOfStudents ++;
        return *this;
    }
};


int CStudent::noOfStudents = 0;

void fn(CStudent& s)
{
    cout << s.nextStudent().noOfStudents << endl;
}

void main()
{
    CStudent ss;
    fn(ss);
}
我想知道:
CStudent& nextStudent()
{
    noOfStudents ++;
    return *this;
}
返回对象引用的函数一般用在什么地方?它有什么作用?
火箭球迷 发表于 2013-6-29 21:54 | 显示全部楼层
你不是自己都示例了吗
支持链式语句啊

另外,像容器返回包含的数据也要用到返回引用
yybj 发表于 2013-6-29 22:11 | 显示全部楼层
设置属性 类似于 obj.SetA().SetB()....
无冕之王 发表于 2013-6-29 22:14 | 显示全部楼层
1)大对象,节约空间。
2)函数连续调用,节约代码。
3)返回一个左值,可以用来修改 *this 对象,或者可以用来修改函数参数。
4)不用考虑空引用,比指针有效率。
baidudz 发表于 2013-6-30 12:37 | 显示全部楼层
无冕之王 发表于 2013-6-29 22:14
1)大对象,节约空间。
2)函数连续调用,节约代码。
3)返回一个左值,可以用来修改 *this 对象,或者可以 ...

分析的很全面
您需要登录后才可以回帖 登录 | 注册

本版积分规则

229

主题

2603

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部

229

主题

2603

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部