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

标签 c++ class constructor copy

这是我得到的:

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/

相关文章:

c++ - (C++) 将指向动态分配数组的指针传递给函数

c++ - bullet 3d 中的滚动摩擦表现不像演示

c++ - 类对象指针不会分配给字符串

javascript - 在javascript中使用子类中的静态方法

objective-c - Objective C 对象的两阶段构建

c++ - Visual Studio 调试器 - 源代码搜索目录

c++ - 通过平方进行模幂运算的溢出可能性

javascript - 如何更新 Javascript 以返回 1

c++ - 为什么我在 main 中声明的变量被初始化,就好像它是我的类的变量一样?

c++ - 在C++中模拟虚拟构造函数