Abstract class and unique pointer

前端 未结 4 952
北海茫月
北海茫月 2021-02-13 21:05

I have the following error in my code:

error: allocating an object of abstract class type \'Material\'

I don\'t know how to handle this case.

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-13 21:44

    The problem is because Mix tries to create an object of the abstract class Material:

    : mat1_(std::make_unique(mat1))
    

    Ideally, based on the signature

    Mix(const Material& mat1, const Material& mat2)
    

    Mix should be able to just operate on any type of Material passed to it.

    The fact that Mix is passed with abstract class reference is good. But the fact that Mix is trying to create objects of derived class is unusual. What if there were other derived classes?

    I would design slightly differently such that Mix is not the owner of the constituents; they are created and owned by something outside, Mix just mixes what is passed to it.

    struct Mix : public Material
    {
      Mix(const Material& mat1, const Material& mat2)
        : mat1_{mat1}, mat2_{mat2}
      {}
    
      virtual int get_color() const override
      {
        return mat1_.get_color() + mat2_.get_color();
      }     
    private:
      Material const& mat1_;
      Material const& mat2_;
    };
    
    int main()
    {
      std::unique_ptr mat1 = std::make_unique();
      std::unique_ptr mat2 = std::make_unique();
    
      auto mix = Mix(*(mat1.get()), *(mat2.get()));
      std::cout << mix.get_color() << '\n';
    }
    

提交回复
热议问题