'不匹配'operator <<''的特殊情况

时间:2019-05-27 10:32:29

标签: c++

我遇到的问题是我已经完成operator <<了,但是由于某种原因它不起作用。我尝试了无数种方法,以下一种对我来说最有意义。但是还是失败了。任何人都可以向我展示在此特定实例中重载(*this)[index]的正确方法(请参阅VisiblePolygon类)?多边形类将由operator <<组成类VisiblePolygon。找不到针对这种特定情况的解决方案。因此,我在这里。谢谢!

编译错误:

In function ‘std::ostream& operator<<(std::ostream&, const Polygon&)’:

polygon.h:103:8: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Object::PointType’)

     os <<p.mpt[i];
     ~~~^~~~~~~~~~

我的代码:

#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <cmath>


class Polygon : public Point 
{
  private:
    Object::PointType *mpt; //An array of points
    int msize; 

  public:
    PointType& operator[](int index)  const
    {
      return mpt[index];
    }

    Polygon(const PointType* points, int npoints); 

    Polygon(PointType* points, int npoints, float depth) //constructor
      : Point(*points,depth),
      mpt{new Object::PointType[npoints]},
      msize(npoints)
    {
       for(int i = 0; i < msize; ++i)
       {
         mpt[i]  = points[i];
       }
    }

    Polygon center() 
    {
      //..
    }

    float x()
    {   
      //...
    }

    float y()
    {
      //...
    }

    int size() const
    {
      return msize;
    }

    virtual void render() const 
    {}

    friend std::ostream& operator<<(std::ostream& os, const Polygon& p)
    {   
      for (int i = 0; i < p.msize; ++i)
      {
        os <<p.mpt[i]; 
        return os;              
      }
    }
};

class VisiblePolygon : public Polygon
{
  public:
    VisiblePolygon(const Object::PointType* points, int size) :
      Polygon(points, size)
    {
    }

    void render() const override
    {
        std::cout << "Polygon with vertices: ";
        for (int index = 0; index < size(); ++index)
        {
            std::cout << (*this)[index] << " ";
        }
        std::cout << std::endl;
    }
};

1 个答案:

答案 0 :(得分:2)

错误

  

In function ‘std::ostream& operator<<(std::ostream&, const Polygon&)’: polygon.h:103:8: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘Object::PointType’)

基本上说:“ 好的,您有operator <<用于Polygon,现在您也需要一个PointType ”。

无关,但是return os;应该在循环之外。