如何在C ++中创建抽象类的数组 [英] how to create array of an abstract class in c++

查看:115
本文介绍了如何在C ++中创建抽象类的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序来接收食物订单并打印出来。我有基类 Food ,其中具有纯虚拟功能。 Class Food有2个子类 Pizza Dessert 。我试图在我的中制作一个 Food 的数组,所以当客户订购 Pizza时 Dessert ,它将存储在 Food 数组中。但是每次我尝试时,都会出现错误。如果我想使用循环遍历客户订购的每个项目,该如何将这两个项目放在一起?
这是我的代码:

I am trying to create a program that takes food order and prints it out. I have my base class Food which has a pure virtual function in it. Class Food has 2 subclass Pizza and Dessert. I am trying to make an array of Food in my main so when a customer orders Pizza or Dessert, it will be stored in the array of Food. But every time I try, I get an error. How should I put the two items together then if I want to use a loop to go over each item the customer ordered? This is my code:

int main()
{
  Dessert d("brownie");
  Pizza p("BBQ delux");
  Food array[2] = {d,p};
}

这是我的错误信息。 (注意: get_set_price() print_food()是我的纯虚函数,在基类中定义并在2个子类)

This is my error message. (NOTE: get_set_price() and print_food() are my pure virtual functions which is defined in base class and implemented in the 2 subclasses)

main.cpp:37:14: error: invalid abstract type ‘Food’ for ‘array’
  Food array[2] = {d,p};

In file included from main.cpp:4:0:
Food.h:5:7: note:   because the following virtual functions are pure within ‘Food’:
 class Food
       ^

Food.h:20:15: note:     virtual void Food::get_set_price()
  virtual void get_set_price()=0;
               ^

Food.h:27:15: note:     virtual void Food::print_food()
  virtual void print_food()=0; 
               ^

main.cpp:37:22: error: cannot allocate an object of abstract type ‘Food’
  Food array[2] = {f,o};
                  ^


推荐答案

您无法创建抽象实例类,但是您可以将具体的派生实例分配给基类的指针或引用。

You cannot create instances of abstract classes, but you can assign concrete derived instances to pointers or references of the base class.

int main()
{
  Dessert d("brownie");
  Pizza p("BBQ delux");
  Food* array[2] = {&d,&p};
}

然后使用 array

array[0]->print_food();

这篇关于如何在C ++中创建抽象类的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆