gpt4 book ai didi

c++ - 我真的不明白为什么我在创建模板类共享指针时出错

转载 作者:行者123 更新时间:2023-11-30 04:46:27 26 4
gpt4 key购买 nike

我不明白我收到的错误消息,也不知道如何解决;

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。但是,当您尝试将 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++;
}

关于c++ - 我真的不明白为什么我在创建模板类共享指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741838/

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