为了对分配到heap的对象进行生命周期控制(new方法创建的对象,假设为类Entity),需要用到智能指针类(假设为ScopePtr)。该类封装了一个指针,指针指向类型为要控制的类。
复制代码
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#include <iostream> class Entity{ public: int x; public: void Print() const { std::cout << "Hello" <<std::endl; } }; class ScopePtr{ private: Entity* m_Obj; public: ScopePtr(Entity* entity) : m_Obj(entity){ } ~ScopePtr(){ delete m_Obj; } }; int main(){ ScopePtr entity = new Entity(); std::cin.get(); }
当需要创建Entity对象时,一般不使用Entity指定类型,而是用ScopePtr。这样可以实现对Entity类型对象的生命周期管理。
复制代码
1ScopePtr entity = new Entity();
但是如果需要调用Entity的类成员方法时,无法如下方法:
复制代码
1entity->fun();
这样使得代码不够简洁,可以采用复写->符号来处理,在ScopePtr类中添加如下方法:
复制代码
1
2
3Entity* operator->(){ return m_Obj; }
这样,就可以直接使用上述写法,完整代码如下:
复制代码
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#include <iostream> class Entity{ public: int x; public: void Print() const { std::cout << "Hello" <<std::endl; } }; class ScopePtr{ private: Entity* m_Obj; public: ScopePtr(Entity* entity) : m_Obj(entity){ } ~ScopePtr(){ delete m_Obj; } Entity* operator->(){ return m_Obj; } }; int main(){ ScopePtr entity = new Entity(); entity->Print(); std::cin.get(); }
最后
以上就是缥缈指甲油最近收集整理的关于c++智能指针对象直接调用封装类的成员方法的全部内容,更多相关c++智能指针对象直接调用封装类内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复