【发布时间】:2009-11-06 12:37:09
【问题描述】:
我想通过避免公共继承将一个类直接添加到一个新类中。例如我有一个像
这样的类class size {
private:
int width;
int height;
public:
void set_width(int w) { width = w; }
int get_width() { return width; }
void set_height(int h) { height = h; }
int get_height() { return height; }
int get_area() { return width*height; }
};
只是想将它的功能插入到这样的新类中
class square : public size {
// ...
};
会写
square s;
s.set_width(10);
s.set_height(20);
cout << "Area of the square: " << s.get_area() << endl;
但是这样我就违反了公共继承的 is-a 规则。我的square 不是size 它has-a size。所以我必须写
class square {
public:
size its_size;
// ...
};
但是现在我最初将size 的功能插入square 的想法丢失了。我要写
square s;
s.its_size.set_width(10);
s.its_size.set_height(20);
cout << "Area of the square: " << s.its_size.get_area() << endl;
或为size 的getter 和setter 添加几个包装器到square。
编辑: 我必须补充:size 注定不会有虚拟析构函数。我不想使用size,它是多态的后代。
编辑 2: 另一个示例:您想编写一个类,它提供与 std::list<T> 相同的接口,但提供的功能比简单的独立函数所能完成的要多得多。标准容器不应被子类化,因此您必须添加 std::list<T> 作为成员并将所有公开提供的 std::list<T> 函数直接包装到您的新类中。这是很多重复性的工作,而且容易出错。
问题: 是否有可能将size 的接口公开加入 square 而不公开继承size。我的square 不应该是size,但应该提供相同的界面(在它自己的部分旁边)。
【问题讨论】: