gpt4 book ai didi

c++ - 如何在类的成员函数中调用复制构造函数?

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:45 25 4
gpt4 key购买 nike

这是我得到的:

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/

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