创建基类指针的向量并将派生类对象传递给它(多态性)
Making a vector of base class pointers and pass Derived class objects to it (Polymorphism)
我正在尝试为我的Shape程序实现一个菜单。我已经实现了所有的形状类。两个直接派生自抽象类"Shape",另外两个派生自一个名为"Polygon"的类,该类派生自"Shape",如下所示:
Shape -> Polygon -> Rectangle, Triangle
`-> Circle, Arrow
在我的菜单类中,我想创建某种数组,该数组可以包含指向对象的指针以及基类"Shape"的类型。但是我不确定如何正确地做到这一点,并且以一种适用于所有形状的方式,因为我的 2 个类不是直接从"Shape"派生的。
这是我的菜单类:
class Menu
{
protected:
//array of derived objects
public:
Menu();
~Menu();
// more functions..
void addShape(Shape& shape);
void deleteAllShapes();
void deleteShape(Shape& shape);
void printDetails(Shape& shape);
private:
Canvas _canvas; //Ignore, I use this program to eventually draw this objects to a cool GUI
};
在函数"addShape(Shape& shape(;"中,我想用它来将每个给定的形状添加到我的数组中。如何实现向其添加新对象?而且,如何检查给定对象是否派生自"多边形"?因为如果是这样,那么据我所知,我需要以不同的方式调用成员函数。
我看到你在菜单中有一个数组,假设:
Shape* myshapes[10];
形状可以是矩形,三角形,圆形等。 你想要的是能够使用菜单的 printDetails(( 方法,如下所示:
void printDetails()
{
for(int i = 0; i < size; i++)
{
cout << "Index " << i << " has " << myshapes[i]->getShapeName() << endl;
}
}
getShapeName(( 将返回一个字符串,例如,如果它是 Rectangle,则返回 "Rectangle"。 您将能够在纯虚拟功能的帮助下做到这一点。纯虚函数必须在抽象类 Shape 中,它具有:
virtual string getShapeName() = 0; //pure virtual
这意味着我们期待在派生类中对此函数进行定义。这样,您将能够使用shapes数组中的Shape指针使用getShapeName((方法,这将告诉您形状是矩形,三角形还是圆形等。
class Shape
{
public:
virtual string getShapeName() = 0;
};
class Circle : public Shape
{
private:
int radius;
public:
Circle(int r) { radius = r; cout << "Circle created!n"; }
string getShapeName() { return "Circle"; }
};
class Arrow : public Shape
{
private:
int length;
public:
Arrow(int l) { length = l; cout << "Arrow created!n"; }
string getShapeName() { return "Arrow"; }
};
class Polygon : public Shape
{
public:
virtual string getShapeName() = 0;
};
class Triangle : public Polygon
{
private:
int x, y, z;
public:
Triangle(int a, int b, int c) { x = a; y = b; z = c; cout << "Triangle created!n"; }
string getShapeName() { return "Triangle"; }
};
class Rectangle : public Polygon
{
private:
int length;
int width;
public:
Rectangle(int l, int w){ length = l; width = w; cout << "Rectangle created!n"; }
string getShapeName() { return "Rectangle"; }
};
要实现 addShape(( 方法,您可以这样做:
void addShape(Shape &shape)
{
myshapes[count] = &shape;
count++;
}
另外,请记住在 addShape(( 方法中通过引用或使用指针传递 Shape。 我希望这有帮助...祝你好运:-(
相关文章:
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- C++多态性:有没有办法找到对象成员函数的地址?
- C++ 被此代码与多态性、指针和对象切片混淆
- 具有多态性的对象声明中的逗号
- 使用多态性时在子对象之间进行转换?
- 多态性的面向对象方法
- 如何使用多态性将相同的操作应用于具有相同基类的不同对象的unordered_sets
- 使用数组对对象的编译时多态性是否可行?
- 多态性并获取C++中的对象类型
- 多态性:通过类文本或对象访问静态成员
- 多态性和对象存储
- C++ 复制具有多态性的对象
- 数组中对象的C++多态性
- 类成员对象的多态性
- C++对象多态性问题
- 如何在具有多态性的函数外部创建对象
- 我可以使用多态性将不同的对象存储在具有C++的数组中吗?
- 多态性c++,当对一个对象进行更改时,所有对象都会更改