嵌套类:如何访问封闭类中的成员变量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了嵌套类:如何访问封闭类中的成员变量相关的知识,希望对你有一定的参考价值。
以下代码片段旨在将所有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]);
}
}
};
答案
你可以修改你的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]);
}
}
};
以上是关于嵌套类:如何访问封闭类中的成员变量的主要内容,如果未能解决你的问题,请参考以下文章