我寫指針使用 (我需要智能指針,但我不能使用升壓或C++ 11)這個模板類:C++:與超載箭頭指針模板的使用( - >)運算符
template<class T>
class TreePointer{
public:
TreePointer(){
isRefOnly=false;
data=NULL;
};
TreePointer(T* data){
this->data=data;
this->isRefOnly=false;
}
TreePointer(const TreePointer& anotherPtr){
this->data=anotherPtr.data;
this->isRefOnly=true;
}
virtual ~TreePointer(){
if (!isRefOnly){
delete data;
}
}
T* operator->() const{
return data;
}
void operator=(const TreePointer &anotherPtr){
this->data=anotherPtr.data;
this->isRefOnly=true;
}
private:
T* data;
bool isRefOnly;
};
而且我有很大的類方法很多,像這樣:
class WrittenBigClassWithManyMethods{
public:
WrittenBigClassWithManyMethods(int v){
this->v=v;
}
int sum(WrittenBigClassWithManyMethods* a){
return v+a->v;
}
int v;
};
我的智能指針的這種用法很好地工作:
TreePointer<WrittenBigClassWithManyMethods> tp(new WrittenBigClassWithManyMethods(5));
WrittenBigClassWithManyMethods* simpleClass=new WrittenBigClassWithManyMethods(5);
cout << tp->sum(simpleClass);
但它的使用是不行的:
TreePointer<WrittenBigClassWithManyMethods> tp2(new WrittenBigClassWithManyMethods(5));
cout << tp->sum(tp2);
如何我可以改變我的模板爲指針,使調用methrod 類WrittenBigClassWithManyMethods的總和與TreePointer類型的參數,而無需任何同類的變化WrittenBigClassWithManyMethods及其任何用法?如果這不可行,我如何最小化類的變更WrittenBigClassWithManyMethods及其用法?
'TreePointer p = makeThingy();'可能不會表現出你想要的樣子。這不是一個智能指針,它是unique_ptr和raw指針的混合,取決於布爾狀態。相反,只需使用unique_ptr和T&。 –
或者只使用'std :: auto_ptr',而不是C++ 11。 –