1

我陷入了一个错误。这是我的代码:

 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 main(int,char**)'中:

smart_pointer_impl.cpp:27: 错误: 没有匹配函数调用'smart_ptr::smart_ptr(xxx*&)'</p>

smart_pointer_impl.cpp:7:注意:候选者是:smart_ptr::smart_ptr(t*) [with t = xxx*]

smart_pointer_impl.cpp:4: 注意: smart_ptr::smart_ptr(const smart_ptr&)

任何解决方案的帮助都是最受欢迎的。

4

4 回答 4

2

大概smart_ptrtemplate<class t>,然后主要是打算smart_ptr<xxx>代替smart_ptr<xxx*>?

于 2013-11-05T15:37:34.300 回答
0

您尚未将您的课程声明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);
于 2013-11-05T15:37:57.047 回答
0

我希望您忘记了代码的第一行,即

 template<class t>

这行:

smart_ptr<xxx *> p1(x1);

应该:

smart_ptr<xxx> p1(x1);
于 2013-11-05T15:42:41.793 回答
0

你需要改变::

smart_ptr<xxx *> p1(x1); to smart_ptr<xxx> p1(x1); 

它会起作用的。

于 2013-11-05T15:54:43.873 回答