【问题标题】:Inheritance with no additional data members没有额外数据成员的继承
【发布时间】:2014-04-21 14:30:16
【问题描述】:

考虑这段代码:

class Basic {
public:
   Basic() { ... }
   Basic(const Basic& other) { ... }
   virtual ~Basic() { ... }

   virtual void foo() = 0;
private:
   int x, y, z;
};

class DerivedA : public Basic {
public:
   DerivedA() :  { ... }
   virtual ~DerivedA() { ... }

   virtual void foo() { ... }
}

class DerivedB : public Basic {
public:
   DerivedB() { ... }
   virtual ~DerivedB() { ... }

   virtual void foo() { ... }
}

实际上,DerivedADerivedB 类没有额外的数据成员,它们的唯一目的是从Basic 类覆盖纯虚拟foo 函数。

我想为 Derived 两个类实现 copy-constructoroperator=

我的计划是:

1) 复制构造函数:

像这样在派生类中实现复制构造函数:

DerivedA(const DerivedA& other) : Basic(other) {
   // Do nothing
}
DerivedB(const DerivedB& other) : Basic(other) {
   // Do nothing
}

2) 赋值运算符:

Basic 类实现交换:

void swap(Basic& other) {
  std::swap(x, other.x);
  std::swap(y, other.y);
  std::swap(z, other.z);
}

为“派生”类重载 operator=:

DerivedA& operator=(const DerivedA& other) {
  Derived tmp(other);
  (*this).swap(tmp);
  return (*this);
} 

DerivedB 也一样

现在我的问题是:这是一个好习惯吗?我应该为两个派生类实现交换吗?在这种继承中是否有更好的方法来实现这些方法?我的架构是否足够好,可以得到其他人的大力支持?

p.s.对不起我的英语。

【问题讨论】:

  • 如果您的代码按预期工作,但您只想对其进行审查以了解最佳实践或完成相同任务的替代方法,则可以将其迁移到 Stack Exchanges 代码审查部分。
  • 如果有人交换()两个不同类型的派生类实例怎么办?还是对一个 Basic 和一个 DerivedA 的引用?似乎为基类定义了 swap() 是令人担忧的。
  • 其实编程子站点更适合更高层次的设计问题。这显然不是代码审查问题。

标签: c++ inheritance


【解决方案1】:

让我提供一个替代建议:使用默认的复制构造函数和复制赋值运算符,让编译器为您完成工作!您的类没有任何浅层状态,因此默认版本将完全按照您的要求进行,并且编译器更可能正确生成,而不是您不会错过某个地方的复制粘贴,从而引入了一个微妙的错误。

【讨论】:

    猜你喜欢
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    相关资源
    最近更新 更多