gpt4 book ai didi

c++ - 嵌套类 : how to access the member variable in enclosed class

转载 作者:行者123 更新时间:2023-11-28 01:39:22 25 4
gpt4 key购买 nike

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

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

然后我将 Point ori 的第 3 行更改为 static Point ori 并将 ori 更改为 Solution::oridistance(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]);
}
}
};

关于c++ - 嵌套类 : how to access the member variable in enclosed class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47959038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com