我被一个错误困住了。这是我的代码:
template<class t>
class smart_ptr{
t *ptr;
public:
smart_ptr(t *p):ptr(p){cout<<"smart pointer copy constructor is called"<<endl;}
~smart_ptr(){cout<<"smart pointer destructor is called"<<endl;delete(ptr);}
t& operator *(){cout<<"returning the * of pointer"<<endl;return(*ptr);}
t* operator ->(){cout<<"returning the -> of pointer"<<endl;return(ptr);}
t* operator=(const t &lhs){ptr=lhs;cout<<"assignement operator called"<<endl;}
};
class xxx{
int x;
public:
xxx(int y=0):x(y){cout<<"xxx constructor called"<<endl;}
~xxx(){cout<<"xxx destructor is called"<<endl;}
void show(){cout<<"the value of x="<<x<<endl;}
};
int main(int argc, char *argv[])
{
xxx *x1=new xxx(50);
smart_ptr<xxx *> p1(x1);
return 0;
}在编译过程中,我会遇到以下错误
smart_pointer_impl.cpp:在函数‘int(int,char**)’中:
smart_pointer_impl.cpp:27:错误:没有调用‘smart_ptr::smart_ptr(xxx*&)’的匹配函数
smart_pointer_impl.cpp:7:注:候选人是: smart_ptr::smart_ptr(t*),t= xxx*
smart_pointer_impl.cpp:4:注: smart_ptr::smart_ptr(const smart_ptr&)
任何解决方案的帮助都是最受欢迎的。
发布于 2013-11-05 15:54:43
你需要改变:
smart_ptr<xxx *> p1(x1); to smart_ptr<xxx> p1(x1); 看起来不错。
发布于 2013-11-05 15:37:34
据推测,smart_ptr是template<class t>,而总体上是smart_ptr<xxx>而不是smart_ptr<xxx*>
发布于 2013-11-05 15:37:57
您还没有将类smart_ptr声明为模板
template <TYPE>
class smart_ptr{
TYPE *ptr;
public:
smart_ptr(TYPE *p):ptr(p){cout<<"smart pointer copy constructor is called"<<endl;}
~smart_ptr(){cout<<"smart pointer destructor is called"<<endl;delete(ptr);}
TYPE& operator *(){cout<<"returning the * of pointer"<<endl;return(*ptr);}
TYPE* operator ->(){cout<<"returning the -> of pointer"<<endl;return(ptr);}
TYPE* operator=(const TYPE &lhs){ptr=lhs;cout<<"assignement operator called"<<endl;}
};另外,您正在声明您的指针类型为‘指针到xxx’,但是模板类是指向类型的指针。尝试:
smart_ptr<xxx> p1(x1);https://stackoverflow.com/questions/19792672
复制相似问题