我正在尝试使用指向函数的指针来实现一个函数的功能,类似于www.cplusplus.com上this link的底部(最后一部分),只是更加高级。我正在尝试以下方法:
在myFile.h
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<>();
for (int i = 0; i < result.size(); i++) {
points.clear();
PolylineOptions lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
在myFile.cpp
// namespace for: Functions
namespace Functions {
// namespace for: 1D functions
namespace OneDimensional {
// Function for: f(x) = x * x, Note: read t as times
double xtx(double x);
}
// namespace for: 2D functions
namespace TwoDimensional {
// Function for: f(x, g(y)) = x + g(y), Note: read _ as "of"
double f_xANDg_y(double x, double(*g)(double y));
}
}
我检查了错误E0020,这使我进入Stack Overflow,该用户缺少括号。我检查了一下,但没有丢失括号(但是即使检查了几次,我还是可能错了。)
是我错误地实现了f(x,g(y))的想法,还是我实际上缺少括号?
答案 0 :(得分:2)
出现此错误是因为编译器不知道什么是“ y”,因为在函数调用的可见范围内未声明任何位置。 'f_xANDg_y(double x,double(* g)(double y);' 上面的功能参数仅包含两个参数,
由于函数中的整个'double(* g)(double y)'参数TwoDimenesional归结为“一个以double作为输入并返回double的函数指针”
double Functions::TwoDimensional::f_xANDg_y(double x, double(*g)(double y)) {
return (x + (*g)(y)); // <== This is where I get the Error (E0020)
}
您的代码工作正常,您将需要在函数中再添加一个“ double”作为参数,如TwoDimensional::f_xANDg_y(double x, double(*g)(double), double y)
所示。如编译器所期望的那样。
'
namespace Functions {
// namespace for: 1D functions
namespace OneDimensional {
// Function for: f(x) = x * x, Note: read t as times
double xtx(double x);
}
// namespace for: 2D functions
namespace TwoDimensional {
// Function for: f(x, g(y)) = x + g(y),a Note: read _ as "of"
double f_xANDg_y(double x, double(*g)(double), double yParam);
}
}
double Functions::OneDimensional::xtx(double x) {
return (x * x);
}
double Functions::TwoDimensional::f_xANDg_y(double x, double(*g)(double), double y) {
return (x + g(y));
}
'