gpt4 book ai didi

c++ - 设备驱动程序和图形的类设计

转载 作者:行者123 更新时间:2023-11-28 05:56:18 24 4
gpt4 key购买 nike

试图组织我认为应该(并且可能是)一些类之间的一组简单关系的东西。 基本上是尝试以一种有意义的方式将 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 类中。我可以在 Counter 类中virtual displayImage() 的一个版本,但我假设这需要 Graphics 总是必须继承 Counter,我并不热衷于此。有没有更好的方法允许 Counter 访问 Graphics 类函数(最终传递给 LCD 驱动程序),同时仍与其保持分离?

最佳答案

为什么要使用继承?

根据您对类(class)的描述,我没有看到它们之间有任何特化/某种关系,这意味着您应该在这种情况下使用组合:

  • 图形 Driver 需要能够显示一些 Image(您的示例中不存在的类型)
  • Graphics 图像加载库需要能够加载 Image
  • Counter 显示应该同时使用 DriverGraphics,两者都在其构造函数中提供,并用它们显示计数器。

这个概念叫做composition over inheritance ,你可以用谷歌获得更多关于它的好文章。 (基本上:OOP 和使用类并不意味着您必须对所有内容使用继承)

关于c++ - 设备驱动程序和图形的类设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34102242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com