我想通过避免公共继承直接将类添加到新类中。比如我有一个像公开添加,但继承私有
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;
但这种方式我m违反是一个规则的公共继承。我的square
不是size
它 has-asize
。所以我必须写
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
,但应该提供相同的界面(靠近它自己的部分)。
是的,我认为这是一个命名问题。除非你想在其他地方使用size class – djeidot 2009-11-06 12:44:29
否,它只是一个例子。我不想多态地使用大小。大小的功能应该简单地添加到方块。 – phlipsy 2009-11-06 12:54:48
请考虑我最新的修改。如果我想将std :: list插入我的课程,会发生什么情况? –
phlipsy
2009-11-06 13:27:26