这是我得到的:
void set::operator =(const set& source)
{
if (&source == this)
return;
clear();
set(source);
}
这是我得到的错误:
vset.cxx:33: error: declaration of 'source' shadows a parameter
我该如何正确执行此操作?
最佳答案
您正在寻找复制交换习语:
set& set::operator=(set const& source)
{
/* You actually don't need this. But if creating a copy is expensive then feel free */
if (&source == this)
return *this;
/*
* This line is invoking the copy constructor.
* You are copying 'source' into a temporary object not the current one.
* But the use of the swap() immediately after the copy makes it logically
* equivalent.
*/
set tmp(source);
this->swap(tmp);
return *this;
}
void swap(set& dst) throw ()
{
// swap member of this with members of dst
}
关于c++ - 如何在类的成员函数中调用复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1844887/