繁体   English   中英

在复制赋值运算符中分配基类成员

[英]Assigning base class members in copy assignment operator

我有一个继承自MSFT类的类,因此无法更改,我希望我的派生类对其复制构造函数和复制赋值运算符具有相同的行为。 我遇到的麻烦是,在复制构造函数中,您可以在初始化列表中为基类调用构造函数,但在运算符中,这不是一个选项。 如何在赋值运算符中正确地重新创建此行为? 仅仅在运算符重载的主体中调用基类的构造函数就足够了吗?

附加说明:基类继承自CObject,它具有operator =(),复制构造函数作为私有和未实现的方法,所以不幸的是,对这些方法的任何调用都将导致编译错误。

我在下面提供了一个简化的代码方案:

类声明:

class Base    
{
protected:
    int baseInt;
public:
    Base(int);
}

class Derived : public Base
{
public:
    Derived(const Derived& other);
    Derived& operator=(const Derived& rhs);
private:
    int derivedInt;
}

派生类成员函数:

// Copy Constructor
Derived(const Derived& other) : Base(5)
{
    derivedInt = other.derivedInt;
}

// Copy Assignment Operator
Derived& operator=(const Derived& rhs)
{
    if (&rhs != this)
    {
        derivedInt = other.derivedInt;
        return *this;
    }
}

编辑:更新语法并添加CObject备注

在一般情况下,您可以通过显式调用operator =作为基类子对象,或者使用copy&swap惯用法(如果可用)来执行此操作:

//explicit call to base operator=
Derived& operator=(const Derived& rhs)
{
  Base::operator=(rhs); //
  derivedInt = rhs.derivedInt;
  return *this;
}


//or copy&swap:
Derived& operator=(const Derived& rhs)
{
  Derived tmp(rhs); //copy
  tmp.swap(*this);
  return *this;
}

void swap(Derived& other)   
{
  Base::swap(other);
  std::swap(derivedInt,other.derivedInt);
}

更新:由于您的基类不是要复制分配的,因此您的派生类也不应该被复制分配。 在某些情况下,类包含不可复制的部分,但完全可复制。 在这些情况下,不可复制的部分不会直接影响类对象的状态,例如唯一的ID。 然后在分配期间通常不会更改这些部件。 但是,在这些情况下,不可复制的部分不应该通过继承来包含,而应该通过聚合来包含。

不久说:Iheritance意味着“是-A”的关系。 您的基地无法复制。 你的派生是一个基础。 因此,您的Derived也无法复制。

像这样

Derived& operator=(const Derived& rhs)
{
    Base::operator=(rhs);
    derivedInt = rhs.derivedInt;
    return *this;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM