在墙上试着整理我认为应该是(并且可能是)一些类之间的简单关系。 基本上试图以一种有意义的方式将3个类组合在一起。
3个类的简化场景:
1 - LCD设备驱动程序 2 - 简单的图形库 3 - 计数器显示类
到目前为止我在伪代码中得到了什么:
class Driver : public Graphics
{
public:
void loadImage(int * image){
// load image into device memory
}
};
class Graphics
{
public:
int image[10];
void displayImage(int * image){
// create/ manipulate image here and...
loadImage(image); //send to device
}
virtual void loadImage(int * image){}
};
class Counter
{
public:
int counterImage[10];
void makeCounter(int * counterImage){
//make a clock counter graphic and…
displayImage(counterImage);
}
};
显然,我还没想出如何将displayImage(counterImage)
函数集成到Counter
类中。我可以在virtual
类中displayImage()
Counter
版本,但我认为这会导致Graphics
始终必须继承Counter
,我并不热衷于此。有没有更好的方法允许Counter
访问Graphics
类函数(最终传递给LCD驱动程序),同时仍然与它分开?
答案 0 :(得分:1)
为什么要使用继承?
根据您对课程的描述,我没有看到他们之间的任何专业化/种类关系,这意味着您应该在这种情况下使用作文:
Driver
需要能够显示一些Image
(示例中不存在的类型)Graphics
图片加载库需要能够加载Image
Counter
显示应同时使用Driver
和Graphics
,两者都在其构造函数中提供,并显示计数器。这个概念被称为composition over inheritance,您可以通过谷歌获得更多关于它的好文章。 (基本上:OOP和使用类并不意味着你必须为所有东西使用继承)