The Arrow Operator in C++
#include <iostream>
#include <string>
class Entity
{
public:
void Print() const { std::cout << "Hello" << std::endl;}
};
class ScopedPtr
{
private:
Entity* m_Obj;
public:
ScopedPtr(Entity* entity)
:m_Obj(entity)
{
}
~ScopedPtr()
{
delete m_Obj;
}
//重载之前
Entity* GetObject() { return m_Obj; }
//重载-> 可以不需要 GetObject()来获取 m_Obj,
//并且可以直接调用 m_Obj 的方法和获取成员(public)
Entity* operator->()
{
return m_Obj;
}
};
struct Vector3
{
float x, y, z;
}
int main()
{
Entity e;
e.Print();
Entity* ptr = &e;
//第一种用法
(*ptr).Print(); //不太美观
ptr->Print(); //用来代替上面的写法 , 也是最常用的用法
//第二种用法
ScopedPtr entity = new Entity();
entity.GetObject()->Print(); //用起来不太美观,这时候我们可以重载->
entity->Print(); //重载之后我们可以直接这么用了
//第三种方法
//可以获取struct 里变量的偏移地址(从0开始) ,Ex: x. offset = 0 ,y. offset =4 ,z. offset =8
int offset = (int) &((Vector3*)0)->x;
std::cout << offset << std::endl;
offset = (int) & ((Vector3*)0)->y;
std::cout << offset << std::endl;
offset = (int) & ((Vector3*)0)->z;
std::cout << offset << std::endl;
}