Abstract class and unique pointer

前端 未结 4 969
北海茫月
北海茫月 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条回答
  •  旧时难觅i
    2021-02-13 21:31

    This call:

    std::make_unique(mat1)
    

    tries to create an instance of class Material, it is irrelevant what type mat1 has. You seem to need method clone() in your class:

    class Material {
    ...
        virtual std::unique_ptr clone() const = 0;
    };
    

    then Mix ctor would be:

    Mix(const Material& mat1, const Material& mat2)
        : mat1_(mat1.clone())
        , mat2_(mat2.clone())
      {}
    

    and you need to implement clone() in every derived class:

    struct Basic : public Material
    {
      Basic() = default;
    
      virtual std::unique_ptr clone() const override
      {
          return std::make_unique( *this ); 
      }
    
      virtual int get_color() const override
      {
        return 1;
      }
    };
    

提交回复
热议问题