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

Nested class: how to access the member variable in enclosed class

本文关键字:成员 变量 访问 何访问 嵌套      更新时间:2023-10-16

以下代码片段旨在将所有points存储在成员函数中,mainFunc将类Solution封闭在priority_queue中(即pq),使得所有points都按照它们到origin的距离按顺序排列。但是,编译器报告错误:

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

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

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]);
}
}
};

您可以修改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]);
}
}
};