【发布时间】:2017-10-07 21:00:46
【问题描述】:
我有自己的智能指针类实现。
template<class 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<class Pointee>
class SmartPtr<SmartPtr<Pointee>> {
private:
Pointee* _pointee;
SmartPtr(SmartPtr &);
public:
explicit SmartPtr(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<class Pointee>
SmartPtr<Pointee>::SmartPtr(SmartPtr &spt) :_pointee(spt.release()) {
return;
}
template<class Pointee>
SmartPtr<Pointee>::SmartPtr(Pointee * pt) : _pointee(pt) {
return;
}
template<class Pointee>
SmartPtr<SmartPtr<Pointee>>::SmartPtr(SmartPtr<Pointee>* pt) : _pointee(pt) {
return;
}
template<class Pointee>
SmartPtr<Pointee>::~SmartPtr() {
delete _pointee;
}
template<class Pointee>
SmartPtr<Pointee>& SmartPtr<Pointee>::operator=(SmartPtr &source)
{
if (&source != this)
reset(source.release());
return *this;
}
template<class Pointee>
Pointee * SmartPtr<Pointee>::release() {
Pointee* oldSmartPtr = _pointee;
_pointee = 0;
return oldSmartPtr;
}
template<class Pointee>
void SmartPtr<Pointee>::reset(Pointee * pt) {
if (_pointee != pt)
{
delete _pointee;
_pointee = pt;
}
return;
}
这个想法是我可以做到这一点:
SmartPtr<SmartPtr<SmartPtr<Time>>> sp3(new SmartPtr<SmartPtr<Time>>(new SmartPtr<Time>(new Time(0, 0, 1))));
Time 这是我自己的测试类。它有方法hours(),它显示在我在构造函数中设置的控制台小时数。
我可以像这样在控制台中显示小时数:
cout << sp2->hours() << endl;
代替:
cout << sp3->operator->()->operator->()->hours() << endl;
我可以这样做,因为我有头等舱,在 opertor->() 我返回 Pointee*。
template<class Pointee>
class SmartPtr {...}
还有
template<class Pointee>
class SmartPtr<SmartPtr<Pointee>> {...}
在opertor->() 我返回Pointee &。
但有些错误我无法修复。
Error C2440 initialization: can not be converted "SmartPtr<Time> *" in "Time *"
Error C2439 SmartPtr<SmartPtr<Time>>::_pointee: unable to initialize member
【问题讨论】:
-
你为什么想要这些?
-
只是为了好玩,但我坚持这个问题
-
对我来说一点也不好玩。更像是火车残骸。
标签: c++ pointers smart-pointers template-specialization