gpt4 book ai didi

c++ - 嵌套智能指针运算符->

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:05 25 4
gpt4 key购买 nike

我有自己的智能指针类实现。

template<typename Pointee>
class SmartPtr {
private:
Pointee* _pointee;
SmartPtr(SmartPtr &);
public:
explicit SmartPtr(Pointee * pt = 0);
~SmartPtr();
SmartPtr& operator=(SmartPtr&);
operator Pointee*() const { return *_pointee; }
bool operator!() const { return _pointee != 0; }
bool defined() const { return _pointee != 0; }
Pointee* operator->() const { return _pointee; }
Pointee& operator*() const { return *_pointee; }
Pointee* get() const { return _pointee; }
Pointee* release();
void reset(Pointee * pt = 0);
};

template<typename Pointee>
SmartPtr<Pointee>::SmartPtr(SmartPtr &spt) :_pointee(spt.release()) {
return;
}

template<typename Pointee>
SmartPtr<Pointee>::SmartPtr(Pointee * pt) : _pointee(pt) {
return;
}

template<typename Pointee>
SmartPtr<Pointee>::~SmartPtr() {
delete _pointee;
}

template<typename Pointee>
SmartPtr<Pointee>& SmartPtr<Pointee>::operator=(SmartPtr &source)
{
if (&source != this)
reset(source.release());
return *this;
}

template<typename Pointee>
Pointee * SmartPtr<Pointee>::release() {
Pointee* oldSmartPtr = _pointee;
_pointee = 0;
return oldSmartPtr;
}

template<typename Pointee>
void SmartPtr<Pointee>::reset(Pointee * pt) {
if (_pointee != pt)
{
delete _pointee;
_pointee = pt;
}
return;
}

在 main.cpp 中我可以这样做:

SmartPtr<Time> sp1(new Time(0, 0, 1));
cout << sp1->hours() << endl;

时间 这是我自己的测试类。它有方法 hours(),它在控制台中显示我在构造函数中设置的小时数。

但是当我想要嵌套智能指针时,我需要这样做:

SmartPtr<SmartPtr<Time>> sp2(new SmartPtr<Time>(new Time(0,0,1)));
cout << sp2->operator->()->hours() << endl;

如何在不使用operator->() 的情况下实现嵌套智能指针?就像这样:

SmartPtr<SmartPtr<Time>> sp2(new SmartPtr<Time>(new Time(0,0,1)));
cout << sp2->hours() << endl;

它也可以不仅是嵌套级别 2,还可以是任何例如:

SmartPtr<SmartPtr<SmartPtr<Time>>> sp3(new SmartPtr<SmartPtr<Time>>(new SmartPtr<Time>(new Time(0, 0, 1))));

我们应该使用:

cout << sp3->hours() << endl;

代替:

cout << sp3->operator->()->operator->()->hours() << endl;

最佳答案

你不能一次使用 operator-> 来到达多个层,除非你专门化 Pointee 来识别 SmartPtr 类型,所以 operator->可以递归写。

否则,只需使用您的 operator* 来清除所有那些嵌套的 operator->() 调用:

cout << (*(*(*sp3))).hours() << endl;

或者

cout << (*(*sp3))->hours() << endl;

关于c++ - 嵌套智能指针运算符->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46620973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com