首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现智能指针类时出错

实现智能指针类时出错
EN

Stack Overflow用户
提问于 2013-11-05 15:33:43
回答 4查看 93关注 0票数 1

我被一个错误困住了。这是我的代码:

代码语言:javascript
复制
 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&)

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-11-05 15:54:43

你需要改变:

代码语言:javascript
复制
smart_ptr<xxx *> p1(x1); to smart_ptr<xxx> p1(x1); 

看起来不错。

票数 0
EN

Stack Overflow用户

发布于 2013-11-05 15:37:34

据推测,smart_ptrtemplate<class t>,而总体上是smart_ptr<xxx>而不是smart_ptr<xxx*>

票数 2
EN

Stack Overflow用户

发布于 2013-11-05 15:37:57

您还没有将类smart_ptr声明为模板

代码语言:javascript
复制
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’,但是模板类是指向类型的指针。尝试:

代码语言:javascript
复制
smart_ptr<xxx> p1(x1);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19792672

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档