读书人

c++中回来对象引用的成员函数有什么用

发布时间: 2013-07-08 14:13:00 作者: rapoo

c++中返回对象引用的成员函数有什么用?
如下代码:


#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;
}

返回对象引用的函数一般用在什么地方?它有什么作用? C++ 引用 对象
[解决办法]
你不是自己都示例了吗
支持链式语句啊

另外,像容器返回包含的数据也要用到返回引用
[解决办法]
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

你不是自己都示例了吗
支持链式语句啊

另外,像容器返回包含的数据也要用到返回引用

链式语句不是只有指针才能实现吗?CStudent* nextStudent()
链式语句不是指->

s.nextStudent().noOfStudents
函数的返回值还可以继续调用
甚至s.nextStudent().nextStudent().nextStudent().nextStudent();
这样无限调用

嗯,明白了。那这种链式语句一般用在什么地方?


操作符重载最常见。
[解决办法]
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

你不是自己都示例了吗
支持链式语句啊

另外,像容器返回包含的数据也要用到返回引用

链式语句不是只有指针才能实现吗?CStudent* nextStudent()
链式语句不是指->

s.nextStudent().noOfStudents
函数的返回值还可以继续调用
甚至s.nextStudent().nextStudent().nextStudent().nextStudent();
这样无限调用

嗯,明白了。那这种链式语句一般用在什么地方?
比较常用的,有string类的连续append,流输入输出的<<和>>操作符


[解决办法]
1)大对象,节约空间。
2)函数连续调用,节约代码。
3)返回一个左值,可以用来修改 *this 对象,或者可以用来修改函数参数。
4)不用考虑空引用,比指针有效率。

读书人网 >C++

热点推荐