c++中回来对象引用的成员函数有什么用
c++中返回对象引用的成员函数有什么用?
如下代码:
我想知道:
返回对象引用的函数一般用在什么地方?它有什么作用?
------解决方案--------------------
你不是自己都示例了吗
支持链式语句啊
另外,像容器返回包含的数据也要用到返回引用
------解决方案--------------------
操作符重载最常见。
------解决方案--------------------
比较常用的,有string类的连续append,流输入输出的<<和>>操作符
如下代码:
#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++
引用
对象
------解决方案--------------------
你不是自己都示例了吗
支持链式语句啊
另外,像容器返回包含的数据也要用到返回引用
------解决方案--------------------
操作符重载最常见。
------解决方案--------------------
链式语句不是指->
你不是自己都示例了吗
支持链式语句啊
另外,像容器返回包含的数据也要用到返回引用
链式语句不是只有指针才能实现吗?CStudent* nextStudent()
s.nextStudent().noOfStudents
函数的返回值还可以继续调用
甚至s.nextStudent().nextStudent().nextStudent().nextStudent();
这样无限调用
嗯,明白了。那这种链式语句一般用在什么地方?