复制派生类的分配运算符



我有一个b类来自A。A实施复制构造函数和分配运算符。我有B的复制构造函数,想实施B。我的方法(很可能是不正确的(是

B& B::operator=(const B& other) {
    B tmp (other);
    std::swap <A>(*this, tmp);
    std::swap (m_member, other.m_member);
}

可以这样的工作吗?我在网上查找了std ::交换为基础类的专业,但没有找到有用的东西。

您可以在如何使用operator = base类中检查此stackoverflow线程(呼叫基类的呼叫运算符...安全?(。

我不明白的是为什么要使用交换。您应该做这样的事情:

B& B::operator=(const B& other) {
    A::operator = (other);
    this->m_member = other.m_member;
    return *this;
}

最新更新