Rin*_*ing 0 c++ constructor copy class
这是我得到的:
void set::operator =(const set& source)
{
if (&source == this)
return;
clear();
set(source);
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
vset.cxx:33:错误:声明'source'会影响参数
我该如何正确地做到这一点?
Mar*_*ork 10
您正在寻找复制交换习语:
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3360 次 |
最近记录: |