【发布时间】:2013-12-24 17:08:45
【问题描述】:
我是一名嵌入式软件工程师,来自位和 C 世界。 在那个世界里,闪存中有数据,用 C 中的 const 表示。RAM 中有数据。 RAM 昂贵且有限,而闪存便宜且足够。此外,由于碎片问题或安全规定,不允许使用 new、delete、malloc 等进行动态内存分配,首选静态设计。
我有大约 2000 个对象,它们具有相似的常量属性但行为不同。 所以对他们来说,我将 Shape Class 定义为一个基类,它包含我的对象的共享属性。为了表示不同的行为,Shape Class 有一个名为 Print() 的抽象方法,它将被父级覆盖。
ShapeList 是重要的部分。它是一个 const 数组,由“const Shapes”组成,因此它们将被链接器放入闪存部分。
下面的程序产生一个输出:
I'm a Shape has 3 dots
I'm a Shape has 4 dots
I'm a Shape has 5 dots
虽然预期的输出是:
I'm a Triangle has 3 dots
I'm a Rectangle has 4 dots
I'm a Pentagon has 5 dots
我需要多态行为。当我打印三角形时,它的行为应该像三角形,而不是形状。我该怎么做?
谢谢。
#include <array>
#include <cstdio>
class Shape
{
public:
const int DotCount;
Shape(const int dot): DotCount(dot) {}
virtual void Print(void) const; // this is virtual method
};
void Shape::Print(void) const
{
printf("I'm a Shape has %d dots\n", DotCount);
}
class Triangle: public Shape
{
public:
Triangle(void): Shape(3) { }
void Print(void) const;
};
void Triangle::Print(void) const
{
printf("I'm a Triangle has %d dots\n", DotCount);
}
class Rectangle: public Shape
{
public:
Rectangle(void): Shape(4) { }
void Print(void) const;
};
void Rectangle::Print(void) const
{
printf("I'm a Rectangle has %d dots\n", DotCount);
}
class Pentagon: public Shape
{
public:
Pentagon(void): Shape(5) { }
void Print(void) const;
};
void Pentagon::Print(void) const
{
printf("I'm a Pentagon has %d dots\n", DotCount);
}
const std::array<const Shape, 3> ShapeList = { Triangle(), Rectangle(), Pentagon() };
int main(void)
{
ShapeList.at(0).Print();
ShapeList.at(1).Print();
ShapeList.at(2).Print();
return(0);
}
更多问题: 今天我意识到虚函数还有另一个问题。当我将任何虚拟函数添加到基类中时,编译器开始忽略“const”指令并将对象自动放置到 RAM 而不是闪存中。我不知道为什么。我已经向 IAR 提出了这个问题。到目前为止我得到的结论是,即使使用堆,ROMable 类也不可能出现多态行为:/
【问题讨论】:
-
它们必须是指针,否则你会得到对象切片en.wikipedia.org/wiki/Object_slicing
-
我没有仔细阅读这个问题。
Also, dynamic memory allocation using new, delete, malloc etc is not allowed due to fragmentation problem or safety regulations, static designs are preferred.根据我的阅读,没有指针或引用是不可能实现多态性的。 -
@juanchopanza:我的问题没有解决方案。
-
请注意,您不一定需要
new或malloc。您只需要将指针存储在数组中。它们指向的对象是否被动态分配是一个正交问题。
标签: c++ arrays polymorphism