【发布时间】: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() { ... }
}
实际上,DerivedA 和DerivedB 类没有额外的数据成员,它们的唯一目的是从Basic 类覆盖纯虚拟foo 函数。
我想为 Derived 两个类实现 copy-constructor 和 operator=。
我的计划是:
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