基础使用场景

-> 属于操作符中的一种,主要针对结构体和类使用

#include<iostream>  
#include<string>  
  
class Entity  
{  
public:  
    void Print() const { std::cout << "Hello!" << std::endl; }  
};  
  
int main()  
{  
    Entity e;  
    e.Print();
    
    Entity* ptr = &e;
    //case 1
    Entity& entity = *ptr;  
    entity.Print();
    //case 2
    (*ptr).Print();  
    *ptr.Print();    //*运算符的优先级低,错误写法  
    
    ptr->Print();    //->符号简化了上述逆向引用的过程  
    }

指针存储的其实只是一个对象地址,为了调用对象函数,不可直接通过 .函数名 调用,需要从地址中获取到实际对象后再调用,-> 只是将这两步复杂的操作简化了

重载的使用

#include<iostream>
#include<string>
 
class Entity
{
public:
	void Print() const { std::cout << "Hello!" << std::endl; }
};
 
class ScoopPtr
{
private:
	Entity* m_entity;
public:
	ScoopPtr(Entity* entity):m_entity(entity)
	{
		
	}
	
	~ScoopPtr()
	{
		delete m_entity;
	}
	
	Entity* operator->()
	{
		return m_entity;
	}
};
 
int main()
{
	ScoopPtr entity = new Entity();
	entity->Print();
}

使用案例

在实际代码开发中,数据通信传输大部分是将数据序列化为字节流的方式,有时会需要知道数据中的某个部分的偏移量时,可以通过 -> 满足上述需求

#include<iostream>  
#include<string>  
  
struct Vector {  
    float x,y,z;  
};  
  
int main()  
{  
    int offset = (int)&((Vector*)nullptr)->x;  
    std::cout << offset << std::endl;  
}

(int)&((Vector*)nullptr)->x 这一行代码按步骤来,先将空指针转换为 Vector 指针,然后访问属性 x ,再通过&取得该属性的内存地址(即在结构体中的偏移量),最后进行转换显示

BUG

因为取得的偏移量为 float,转换为 int 时存在精度丢失,可能会报错