嵌套类:如何访问封闭类中的成员变量

时间:2017-12-24 08:02:51

标签: c++ class nested

以下代码段旨在将所有points存储在priority_queue(即mainFunc)中的封闭类Solution的成员函数pq中,以便全部{{ 1}}按照与points的距离顺序排列。但是,编译器报告错误:

  

origin

然后我将error: invalid use of non-static data member 'Solution::ori'的第3行更改为Point ori并在static Point ori函数中将ori更改为Solution::ori,发生链接错误:< / p>

  

distance(Point p)

有人可以帮我这个吗?提前谢谢!

undefined reference to 'Solution::ori'

1 个答案:

答案 0 :(得分:2)

您可以修改Comparator声明,使其在其构造函数中获得某个Point值:

class Solution {
private:
    Point ori;
    class Comparator {
    public:
        // Save the value in the functor class
        Comparator(const Point& origin) : origin_(origin) {}

        // calculate the euclidean distance between p and origin
        int distance(Point p) {
            return pow(p.x-origin_.x, 2) + pow(p.y-origin_.y, 2);
        }
        // overload the comparator (), the nearest point to 
        // origin comes to the first
        bool operator() (Point l, Point r) {
            if (distance(l) > distance(r)) {
                return true;
            }
        }        
    private:
         Point origin_;
    };

public:
    /*
     * @param points: a list of points
     * @param origin: a point
     */
    void mainFunc(vector<Point> points, Point origin) {
        ori = origin;
        priority_queue<Point, vector<Point>> pq(Comparator(ori));
                                             // ^^^^^^^^^^^^^^^ 
                                             // Pass an instance of 
                                             // the functor class
        for (int i = 0; i < points.size(); i++) {
            pq.push(points[i]);
        }
    }
};