c++ - 我真的不明白为什么在创建模板类共享指针时出现错误
问题描述
我不明白我收到的错误消息,我不知道如何解决;
template<typename T>
class shared_pointer
{
private:
static int howManyObjects;
T* pointer;
public:
shared_pointer( T* p=nullptr)
{
pointer=p;
}
shared_pointer( shared_pointer& a)
{
a.pointer=this->pointer;
howManyObjects++;
}
~shared_pointer()
{
if(howManyObjects==1) delete pointer;
}
T& operator *()
{
return *pointer;
}
T* operator ->()
{
return pointer;
}
};
template<typename T>
int shared_pointer<T>::howManyObjects=0;
int main()
{
int b=5;
int* wsk=&b;
shared_pointer<int> a= shared_pointer<int>(wsk);
return 0;
}
错误信息:
main.cpp: In function ‘int main()’:
main.cpp:10:25: error: cannot bind non-const lvalue reference of type ‘shared_pointer<int>&’ to an rvalue of type ‘shared_pointer<int>’
shared_pointer<int> a= shared_pointer<int>(wsk);
In file included from main.cpp:2:0:
smartpp.cpp:14:2: note: initializing argument 1 of ‘shared_pointer<T>::shared_pointer(shared_pointer<T>&) [with T = int]’
shared_pointer( shared_pointer& a)
解决方案
您的问题出在复制构造函数中:
shared_pointer( shared_pointer& a)
{
a.pointer = this->pointer;
howManyObjects++;
}
所以,根据参数a的类型前面的空格,你可能知道它必须是复制构造函数规则的const。但是,当您尝试将 a 放在那里时,会出现const
以下错误:
shared_pointer(const shared_pointer& a)
{
a.pointer = this->pointer; // Compilation error: assignment of member ‘shared_pointer<int>::pointer’ in read-only object
howManyObjects++;
}
因此,您尝试删除const
并收到您在帖子中显示的错误。问题不在于您试图放在那里的 const ,而是分配方向。您不想修改参数值,而是修改当前对象值。将您的复制构造函数更改为以下内容,一切都会好起来的:
shared_pointer(const shared_pointer& a)
{
this->pointer = a.pointer; // Pay attention that this get the value of a, and not the opposite.
howManyObjects++;
}
推荐阅读
- python - threading code.InteractiveInterpreter 并在执行命令时获取输出
- ffmpeg - ffmpeg推视频成功了,为什么一开始就出错了?
- java - 使用构造函数注入的组件测试问题
- python - 如何使用网页上的按钮调用类的方法 - Django -python
- amazon-web-services - VPN 站点到站点选项中的“内部隧道 IPv4 CIDR”是什么意思?
- reactjs - 我应该如何解决“预计在箭头函数结束时返回一个值。”?
- codeigniter - 在 codeigniter 3 中调用未定义的方法 CI_DB_mysqli_driver::prepare()?
- python - 从 app.py 到 html 的 for 循环返回未知
- javascript - react函数组件有return,但它返回void
- c# - 是否有像 dapper 这样的 .net 本机类/方法发出缓存类型属性来获取/设置值?