how to create array of an abstract class in c++

后端 未结 4 1680
无人及你
无人及你 2020-12-11 18:39

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 sub

4条回答
  •  孤城傲影
    2020-12-11 18:59

    You need reference semantics for that, because Food arr[2]; tries to initialize the array with default values (which are abstract, thus not constructible).

    I think std::array, 2> arr; should be the most natural to use in this case.

    std::array> arr = {
        std::make_unique("brownie"),
        std::make_unique("BBQ delux")
    };
    

    If you just want to loop over those two values, though, using initializer_list would be easiest, I suppose.

    for (auto f : std::initializer_list{&d,&p})
        f->commonMemberFunction();
    

    Unfortunately it won't deduce the correct type from just {}, but a helper could be created, I suppose,

提交回复
热议问题