代码之家  ›  专栏  ›  技术社区  ›  code

如何添加最终重写器

  •  2
  • code  · 技术社区  · 7 年前

    如何添加“最终重写器”来解决此问题?

    #include <iostream>
    
    struct Shape
    {
      virtual void print()
      {
        std::cout << "SHAPE" << std::endl;
      }
      virtual ~Shape() {}
    };
    
    struct Box : public virtual Shape
    {
      void print() 
      {
        std::cout << "BOX" << std::endl;
      }
    };
    
    struct Sphere : public virtual Shape
    {
      void print() final override
      {
        std::cout << "SPHERE" << std::endl;
      }
    };
    
    struct GeoDisc : public Box, public Sphere
    {
    };
    
    int main(int argc, char** argv)
    {
      Shape* s = new GeoDisc;
    
      s->print();
    
      delete s;
    
      return 0;
    }
    

    这是错误消息:
    31:8:错误:“GeoDisc”中的“virtual void Shape::print()”没有唯一的最终重写器

    1 回复  |  直到 7 年前
        1
  •  0
  •   Swift - Friday Pie    7 年前

    关键字 final 在虚拟方法中,声明可以防止多重继承,所以如果我试图解决这种情况下的歧义,这是一种错误的方法。如果长方体和球体都有最后一个字,则会出现错误“virtual function”Shape::print“在“GeoDisc”中有多个最终重写器”。法律含糊不清的解决办法是:

    struct Sphere : public virtual Shape
    {
      void print() override
      {
        std::cout << "SPHERE" << std::endl;
      }
    };
    
    struct GeoDisc : public Box, public Sphere
    {
      void print() final override
      {
        Sphere::print();
      }
    };