C++学习笔记(二十八):c++ 箭头->运算符
- c++中->运算符主要包含两种使用方式,一种是最为常用的用来调用类指针对象的属性和方法,另一种是c++运算符重载。代码示例如下:
-
#include <iostream> class Entity { public: void Print() const { std::cout << "Hello!" << std::endl; } }; class ScopeEntity { private: Entity* m_Obi; public: ScopeEntity(Entity* entity) :m_Obi(entity) {} ~ScopeEntity() { delete m_Obi; } Entity* operator-> () { return m_Obi; } const Entity* operator-> () const { return m_Obi; } }; int main() { //->操作符的使用方式1 const Entity* e1 = new Entity; e1->Print(); //->操作符的使用方式2,操作符重载 const ScopeEntity entity(new Entity); entity->Print(); std::cin.get(); return 0; }
-
箭头操作符在实际项目中一个简单的使用技巧:
-
#include <iostream> struct Vector3 { float x, y, z; }; int main() { //获取结构体Vector对象的每个属性的偏置 //将一个空指针强制类型转换成一个Vector3类型的指针,这样操作使得该Vector3类型的指针的内存地址从0开始 int index =(int) &((Vector3*)0)->y; std::cout << index << std::endl; std::cin.get(); return 0; }