gpt4 book ai didi

c++ - 实现智能指针类时出错

转载 作者:行者123 更新时间:2023-11-30 04:12:34 25 4
gpt4 key购买 nike

我卡在了一个错误上。这是我的代码:

 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*&)’

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&)

欢迎提供解决方案的任何帮助。

最佳答案

大概是smart_ptrtemplate<class t>然后主要是smart_ptr<xxx>而不是 smart_ptr<xxx*>

关于c++ - 实现智能指针类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19792672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com