嵌套类:如何访问封闭类中的成员变量
Nested class: how to access the member variable in enclosed class
以下代码片段旨在将所有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]);
}
}
};
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查