下面是我的代码:
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(const smart_ptr &sm){cout<<"copy constructor is called"
<<endl;ptr=sm->ptr;}
~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->ptr;cout<<"assignement operator called"
<<endl;return *this;}
};
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> p2(new xxx(60));
smart_ptr<xxx> p1(x1);
p1->show();
smart_ptr<xxx> p3(p2); //calling copy construcotr is giving error
p3=p1; //calling assignment operator is giving error
p2->smart_ptr<class xxx>::~smart_ptr<class xxx>(); //calling smart pointer
destructor gives error
return 0;
}
由于错误的复制构造函数、赋值运算符和析构函数代码,我在编译此文件时遇到编译错误。
错误是:
smart_pointer_impl.cpp: In function ‘int main(int, char**)’:
smart_pointer_impl.cpp:33: error: ‘smart_ptr<xxx>’ is not a base of ‘xxx’
smart_pointer_impl.cpp: In copy constructor ‘smart_ptr<t>::smart_ptr(const
smart_ptr<t>&) [with t = xxx]’:
smart_pointer_impl.cpp:28: instantiated from here
smart_pointer_impl.cpp:8: error: passing ‘const smart_ptr<xxx>’ as ‘this’ argument
of ‘t*
smart_ptr<t>::operator->() [with t = xxx]’ discards qualifiers
smart_pointer_impl.cpp:8: error: ‘class xxx’ has no member named ‘ptr’
请找出我在上述功能中的错误之处。欢迎任何帮助。