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

问题描述 投票:0回答:1

以下代码片段旨在将所有points存储在priority_queue(即mainFunc)中包含类Solution的成员函数pq中,以便所有points根据它们与origin的距离按顺序排列。但是,编译器报告错误:

error: invalid use of non-static data member 'Solution::ori'

然后我将Point ori的第3行更改为static Point ori并在ori的函数中将Solution::ori更改为distance(Point p),发生链接错误:

undefined reference to 'Solution::ori'

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

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */

class Solution {
private:
    Point ori;
    class Comparator {
    public:
        // calculate the euclidean distance between p and ori
        int distance(Point p) {
            return pow(p.x-ori.x, 2) + pow(p.y-ori.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;
            }
        }        
    };

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>, Comparator> pq;
        for (int i = 0; i < points.size(); i++) {
            pq.push(points[i]);
        }
    }
};
c++ class nested
1个回答
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]);
        }
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.