c++ - operator-> 有什么特别之处,它是如何工作的?
问题描述
#include <iostream>
class A
{
public:
int a;
int b;
int c;
int d;
};
class B
{
A a;
public:
B(int a, int b, int c, int d) : a{ a, b, c, d } {}
A* operator->()
{
return &a;
}
A* operator++(int)
{
return &a;
}
A* pointer()
{
return &a;
}
};
int main()
{
B b(1, 2, 3, 4);
//std::cout << b->->a << ' ' << b->->b << ' ' << b->->c << ' ' << b->->d << std::endl;
std::cout << b->a << ' ' << b->b << ' ' << b->c << ' ' << b->d << std::endl;
// std::cout << b.pointer()a << ' ' << b.pointer()b << ' '
// << b.pointer()c << ' ' << b.pointer()d << std::endl;
std::cout << b.pointer()->a << ' ' << b.pointer()->b << ' '
<< b.pointer()->c << ' ' << b.pointer()->d << std::endl;
//std::cout << b++a << ' ' << b++b << ' ' << b++c << ' ' << b++d << std::endl;
std::cout << b++->a << ' ' << b++->b << ' ' << b++->c << ' ' << b++->d << std::endl;
}
在这段代码中operator->
,函数pointer
返回完全相同的东西。但是,当我调用时,operator->
我可以将b
其视为实际指针。而如果我调用该函数pointer
,我必须使用箭头运算符来访问a
. 这也适用于operator++
。这是一种独特的行为operator->
吗?如何operator->
工作?
解决方案
是的,这对于重载是特殊的operator->
。
(强调我的)
如果提供了用户定义的 operator->,则在返回的值上再次调用 operator->,递归地,直到到达返回普通指针的 operator->。之后,将内置语义应用于该指针。
这意味着成员访问 like最后->a
应用于返回的指针A*
。
推荐阅读
- python - Scipy 插值/外推样条
- javascript - 使用 D3 库进行动态过滤
- python-3.x - python-igraph:根据顶点位置在图中查找相交边
- javascript - 从 HTML 中的网络摄像头获取视频帧并将其用于 OPENCV python
- jquery - 如何使用 Vue 淡入淡出
- azure - 网络子网的 Azure 策略
- docker - 在 kubernetes 中运行最新的 elasticsearch 集群
- php - Laravel 5.8 获取属于用户的表
- visual-studio-code - 文件问题的自定义问题匹配器
- java - 外部静态 html 视图解析器 + thymeleaf