无法调用内部类对象的向量

时间:2018-11-22 08:53:44

标签: c++

我有一个类,我试图用Point2D对象向量构造该类。

        class Polygon{//Polygon.h
            public:
              //-----------POINT CLASS----------
              class Point2D{
              public:
                Point2D(double param_x = 0, double param_y = 0);
                double getX() const;
                double getY() const;
                void setX(double setX);
                void setY(double setY);
              private:
                double x;
                double y;
              };
            Polygon(vector<Polygon::Point2D>& pointVec);
            private:
                int capacity;
                Point2D* points;//For dynamic array
           }

Polygon::Polygon(vector<Polygon::Point2D>& pointVec){//Vector constructor from polygon.cpp
  capacity = pointVec.size();
  points = new Polygon::Point2D[capacity];
  for(int i = 0; i < capacity; i++)
    points[i] = pointVec[i];
}//Vector of 2D points

但是当我尝试用Point2D对象的向量构造Polygon对象的对象时,它给我一个类似的错误

error: no match for call to '(Polygon) (std::vector<Polygon::Point2D>&)'
    return newPoly(newObj);

在这里,newPoly是Polygon对象,而newObj是Point2D对象的向量。

这是代码出错的地方。

const Polygon Polygon::operator +(const Polygon& otherPoly) const{
 vector<Polygon::Point2D> newObj;
 Polygon newPoly;
 if(capacity > otherPoly.getCapacity()){
   for(int i = 0; i < otherPoly.getCapacity(); i++){
     Point2D obj(points[i].getX() + otherPoly[i].getX(), points[i].getY() + otherPoly[i].getY());
     newObj.push_back(obj);
   }
   for(int j = otherPoly.getCapacity() + 1; j < capacity; j++){
     Point2D obj_2(points[j].getX() + otherPoly[j].getX(), points[j].getY() + otherPoly[j].getY());
     newObj.push_back(obj_2);
   }

   return newPoly(newObj);

 } else if(capacity < otherPoly.getCapacity()){
   for(int i = 0; i < capacity; i++){
     Polygon::Point2D obj(points[i].getX() + otherPoly[i].getX(), points[i].getY() + otherPoly[i].getY());
     newObj.push_back(obj);
   }
   for(int j = capacity + 1; j < otherPoly.getCapacity(); j++){
     Polygon::Point2D obj_2(points[j].getX() + otherPoly[j].getX(), points[j].getY() + otherPoly[j].getY());
     newObj.push_back(obj_2);
   }

   return newPoly(newObj);

 } else if(capacity == otherPoly.getCapacity()){
   for(int i = 0; i < capacity; i++){
     Polygon::Point2D obj(points[i].getX() + otherPoly[i].getX(), points[i].getY() + otherPoly[i].getY());
     newObj.push_back(obj);
   }

   return newPoly(newObj);

 }
}

2 个答案:

答案 0 :(得分:1)

您尚未在类中声明Polygon(vector<Polygon::Point2D>& pointVec)构造函数。尝试添加

Polygon(vector<Polygon::Point2D>& pointVec);

进入多边形类声明

答案 1 :(得分:1)

您正在呼叫return newPoly(newObj)。这不是在调用Polygon的{​​{1}}构造函数。这会尝试在vector中找到一个operator(std::vector<Point2D>)。如果要调用构造函数,则需要Polygonreturn Polygon(newObj);