C++类的返回值是*this的成员函数问题
作者:棉猴 时间:2023-02-01 19:52:50
C++类返回值是*this成员函数
当C++类的成员函数其返回值是*this时,表示返回值是调用该成员函数的变量的引用。
例如:
class A
{
public:
A& func1() {
return *this;
}
int i{0};
}
此时,类A的成员函数func1的返回值是*this,该成员函数的返回值类型是A&。
1 返回值是左值
func1()函数的返回值是类型A的引用,该返回值是左值。也就是说,此时返回的是调用该函数的对象本身,通过该返回值可以调用该对象的其他成员函数或者对其他成员变量进行赋值。
A a;
a.func1().i = 10;
此时类A的对象a的成员变量i的值是10。
2 const成员函数的返回值
在const成员函数中,不能修改对象的成员变量。当const成员函数返回值是*this时,表示返回的是一个const对象的引用。
const A& func2()const {
return *this;
}
其中,func2()函数是类A的const成员函数,该函数的返回值类型是const A&,而不是A&。此时,如果通过func2()函数的返回值修改对象的成员变量
a.func2().i = 100;
此时的报错信息为“error C3892: “a”: 不能给常量赋值”。
对C++类成员返回语句return *this的理解
经常会在类似 copy-assignment 的成员函数看到返回语句 return *this ,这类函数通常返回类型是所属类的引用。
类成员函数的隐式指针 class *this const 经过 *this的解引用后成为此对象本身。此时若成员函数返回类型是 class ,那么返回的将是 this 指向的对象实体的拷贝;
若返回类型是 class& ,那么将返回一个绑定在 this 指向的对象实体上的引用。
来源:https://blog.csdn.net/hou09tian/article/details/108862875
标签:C++类,返回值,this,成员函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android自定义View模仿即刻点赞数字切换效果实例
2023-08-26 12:45:39
![](https://img.aspxhome.com/file/2023/6/110706_0s.gif)
Android SharedPreferences存储用法详解
2023-08-07 08:25:34
![](https://img.aspxhome.com/file/2023/8/83528_0s.gif)
深入了解Hadoop如何实现序列化
2023-10-13 10:33:43
![](https://img.aspxhome.com/file/2023/8/62348_0s.png)
冒泡排序算法原理及JAVA实现代码
2022-08-13 10:30:40
C#中使用HttpDownLoadHelper下载文件实例
2023-05-13 13:13:14
Java MongoDB数据库连接方法梳理
2023-11-25 01:01:20
![](https://img.aspxhome.com/file/2023/8/59538_0s.png)
使用spring框架实现数据库事务处理方式
2022-03-01 14:38:13
![](https://img.aspxhome.com/file/2023/8/62738_0s.png)
Hibernate三种状态和Session常用的方法
2021-11-28 15:04:43
![](https://img.aspxhome.com/file/2023/7/78307_0s.jpg)
C#操作INI文件的辅助类IniHelper
2022-04-18 07:55:34
使用Stargate访问K8ssandra的过程之Springboot整合Cassandra
2022-02-08 23:12:25
![](https://img.aspxhome.com/file/2023/0/67170_0s.jpg)
java的线程池框架及线程池的原理
2023-11-16 22:04:51
Android 仿微信自定义数字键盘的实现代码
2021-10-06 06:58:54
![](https://img.aspxhome.com/file/2023/7/137907_0s.gif)
mybatis group by substr函数传参报错的解决
2022-09-10 03:44:34
解析Java线程同步锁的选择方法
2023-02-08 11:02:32
C#实现简单点餐系统
2021-06-27 22:00:56
![](https://img.aspxhome.com/file/2023/2/80122_0s.jpg)
Android studio中生成引用.aar和.jar的方法详解
2023-09-29 07:48:33
![](https://img.aspxhome.com/file/2023/3/82393_0s.png)
C# Dictionary的使用实例代码
2021-07-29 14:02:02
Android录制声音文件(音频)并播放
2023-07-04 06:31:19
![](https://img.aspxhome.com/file/2023/5/117135_0s.jpg)
深入理解C++中public、protected及private用法
2023-07-02 11:30:17
java格式化数字操作 NumberFormat及DecimalFormat
2023-02-23 22:03:23
![](https://img.aspxhome.com/file/2023/6/116176_0s.png)