简体   繁体   English

静态多态问题

[英]Static Polymorphism Issue

I am on a micro controller (which means I can only have static memory allocation) and I am trying to work with inheritance.....我在一个微控制器上(这意味着我只能有静态内存分配)并且我正在尝试使用继承.....

Suppose I have a abstract class Image and an abstract class Font .假设我有一个抽象类Image和一个抽象类Font An instance of Font can return an Image based off of the char given in a function like so: Font的实例可以根据函数中给出的char返回Image ,如下所示:

Font* mf;
Image* image = mf->GetImage("a");

Now the real issue is I have no idea what to do for the GetImage Function.现在真正的问题是我不知道要为GetImage函数做什么。

The problem is this: in c++ for you to have a member of an abstract class you have to use it as a pointer.问题是这样的:在 C++ 中,为了让您拥有抽象类的成员,您必须将其用作指针。 So my dilemma is that I have a Font which wants to create a new Image and then return it.所以我的困境是我有一个Font想要创建一个新Image然后返回它。

If it returns a pointer to its newly created Image you are returning a reference to a temporary object:如果它返回指向其新创建的Image的指针,则您将返回对临时对象的引用:

Image* FontImpl::GetImage(char c){
  return &ImageImpl(c);  //This object is destroyed once this function exits
}

And then if I return I try to return an actual type like this:然后,如果我返回,我会尝试返回这样的实际类型:

Image FontImpl::GetImage(char c){
  return ImageImpl(c);   //Cannot cast from ImageImpl to Image
}

So is there an idiom or something for this kind of static memory problem?那么对于这种静态内存问题是否有成语或其他东西?

Using dynamic allocation would be easiest but if that's not possible, you have to store the instance somewhere outside the function, eg:使用动态分配将是最简单的,但如果不可能,您必须将实例存储在函数之外的某个地方,例如:

static ImageImpl image;

Image& FontImpl::GetImage(char c) {
  image = ImageImpl(c);
  return image;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM