概述及常规用法

箭头操作符在c++中是一个提供方便的操作符,特别是在类的实例化过后与指针配合使用时作用尤为突出,在使用指针指向一个实例后,我们无法直接调用其中的成员函数,究其原因是我们的指针不是具体的实例,无法调用其中的成员函数。

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>

class Entity
{
private:
int x;
public:
void Print() const//如果使用的const创建的,此处也要有const
{
std::cout << "Hello!" << std::endl;
}
};

class Scopedstr
{
private:
Entity* m_Obj;
public:
Scopedptr (Entity* other)
:m_Obj(other)
{}
~Scopedptr()
{
delete m_Obj;
}

//重载->
Entity* operator->()
{
return m_Obj;
}

const Entity* operator->() const//如果创建时使用的为const则提供const版本
{
return m_Obj;
}
//传出m_Obj
Entity* GetObject(){ return m_Obj;}
};

int main()
{
Scopedptr entity=new Entity();//此处构建的Scopedptr会自动释放空间
//第一种方式传递出类中的m_Obj再调用
entity.GetObject()->Print();
//第二种方式用重载
entity->Print();
}


箭头操作符的特殊用法

在结构体中我们在结构体中定义的变量方式顺序不同也会导致他们的存储地址在内存中的偏移量不同,如 float x,y,z 和float x,z,y在内存中偏移量是相反的(互换),即在第一个中x为0,y为4,z为8,而在第二个中z为4,y为8.此时我们需要知道每个成员偏移量时可以利用->符号来得到每个变量的相对偏移量

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

struct Vector3
{
float x,y,z;
};

int main()
{
int offest1 = (int)&((Vector3*)0)->x;//计算x的偏移量
int offest2 = (int)&((Vector3*)0)->y;//计算y的偏移量
int offest3 = (int)&((Vector3*)0)->z;//计算z的偏移量
std::cout << offest1 << std::endl;
std::cout << offest2 << std::endl;
std::cout << offest3 << std::endl;
}

得到的结果为:

image-20240920131542199

即我们得到了x,y,z三个的偏移量


资料参考:

youtube上the cherno的cpp系列教学