【发布时间】:2020-09-19 23:46:26
【问题描述】:
我为= 运算符编写了以下函数:
Set& Set::operator=(const Set& s)
{
delete[] data;
data=new int [s.size];
size=s.size;
maxSize=s.size;
for (int i=0;i<size;i++)
{
data[i]=s.data[i];
}
return *this;
}
但是,我希望以下代码按预期工作(不删除当前数据):
Set s1,s2;
s1=s1;
所以我做了以下更改:
Set& Set::operator=(const Set& s)
{
if (this == &s)
{
return *this;
}
delete[] data;
data=new int [s.size];
size=s.size;
maxSize=s.size;
for (int i=0;i<size;i++)
{
data[i]=s.data[i];
}
return *this;
}
我的问题是:
1.为什么这是正确的:
if (this == &s)
{
return *this;
}
虽然不是这样:
if (this == s)
{
return *this;
}
s 是一个引用,所以它是内存中的一个位置,不需要使用&operator 来处理它
2.我们可以写下面的内容而不是上面显示的内容:
if (*this == s)
{
return *this;
}
【问题讨论】:
-
this是指针,s是引用,所以this == s试图比较指针和非指针。 -
最好使用自分配安全方法:
Set& Set::operator=(Set const& s) { size = s.size; auto new_data = new int[size]; std::copy(s.data, s.data + size, new_data); delete[] data; data = new_data; return *this; }
标签: c++ class operator-overloading operators equals