【问题标题】:Accessing private vector in the header file within the class访问类内头文件中的私有向量
【发布时间】:2013-07-07 07:27:40
【问题描述】:

我正在尝试访问我的类 Polygon.cpp 中的头类 Polygon.h 中的私有向量数组,我尝试使用 getter,但它不允许我使用类本身的实例调用该函数。我该怎么办?

#include <string>
#include <vector>
#include "point.h"

class Polygon {

private:
    std::vector<Point> pts;
public:

    Polygon();
    static Polygon parsePolygon(std::string s);
    std::string toString() const;
    void move(int dx, int dy);
    double perimeter() const;
    double area() const;
    int getNumVertices() const;
    bool operator == (const Polygon &p) const;
    double isperimetricQuotient() const;
    Point getIthVertex(int i) const {return pts[i];}
    std::vector<Point> const &getPolygon() const {return pts;}
};

//Polygon.cpp

#include "Polygon.h"
#include <string>

Polygon::Polygon()
{
    pts.resize(4);
    Point p1(-1,1); 
    Point p2(1,1);
    Point p3(1,-1);
    Point p4(-1, -1);
    pts[0] = p1;
    pts[1] = p2; 
    pts[2] = p3;
    pts[3] = p4;

}



static Polygon parsePolygon(std::string s)
{
int seperator;
int start = 1;
for(int i = 0; seperator != std::string::npos; i++)
{
seperator = s.find(")(");
std::string subPoint = s.substr(start, seperator);
getIthVertex(i) = Point.parsePoint(subPoint);
start = seperator + 1;
}

}

void move(int dx, int dy)
{
for(int i = 0; i < *this.getPolygon().size(); i++)
{

}
}

【问题讨论】:

  • 你的 cpp 的 parsePolygon 是一个独立于类中的函数。与move 相同。
  • std::vector&lt;Point&gt; const &amp;() const {return pts;} 是什么?您的void move(int dx, int dy) 也是免费功能。
  • @billz,我认为有人忘记命名函数了。
  • 为什么不写一个只有你遇到问题的方法的小类,而不是发布大部分不相关的代码?
  • parsePolygon 看起来更像是一个免费功能,我希望它可以使用const Polygon &amp;

标签: c++ vector private


【解决方案1】:

有很多问题。一个明显的问题是在move() 成员函数的定义中。它从来没有真正定义过:你有一个同名的非成员函数。所以,你必须在Polygon 范围内定义它。接下来,*this.size() 并没有像你认为的那样做:它被解析为*(this.size())。反正你不需要this,这样很容易修复:

void Polygon::move(int dx, int dy)
{
  for(int i = 0; i < getPolygon().size(); ++i)
  {

  }
}

你对parsePolygon的定义也有类似的问题,应该是

Polygon Polygon::parsePolygon(std::string s)
{
  ......
}

【讨论】:

  • 太棒了!非常感谢。现在来解决其他问题:(
  • @user2557642 通常一次处理一个问题会更有效率。因此,下次您发布问题时,请尝试创建一个仅单独重现一个问题的小型代码示例。人们会更容易提供这样的帮助,而且您甚至可以在此过程中自己解决问题。
  • 会的。多谢!但是我们如何让 parsePolygon 也被包含在内。我尝试将范围添加到它,但它会生成一个错误,说“当我尝试“Polygon::parsePolygon()”时声明是兼容的
【解决方案2】:

parsePolygon 的定义应该是:

Polygon  Polygon::parsePolygon(std::string s) {
    ....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2011-02-17
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多