以下是我的代码:
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’
请在上述功能中找到我错的地方。欢迎任何帮助。
答案 0 :(得分:3)
一个明显的错误是您的赋值运算符应该接受并返回对smart_ptr
的引用,而不是t
:
smart_ptr& operator = (const smart_ptr& lhs)
//^^^^^^^^^ ^^^^^^^^^
接下来,复制构造函数在应该调用sm->ptr
时调用sm.ptr
,因为->
已经过载而无论如何都会返回t
:
smart_ptr(const smart_ptr& sm) : ptr(sm.ptr) { .... }
答案 1 :(得分:2)
编译错误可以通过以下更改修复:
// copy ctor
smart_ptr(const smart_ptr &sm)
: ptr(sm.ptr)
{
cout<<"copy constructor is called" << endl;
}
// destructor's invocation
p2.~smart_ptr();
然而,复制构造函数中存在逻辑错误,因为基础对象将被删除两次(或更多次)。