【发布时间】:2017-09-25 19:14:44
【问题描述】:
我查看了以下主题,但它们似乎无助于解决问题:
Function pointer to member function - 这个线程没有帮助,因为访问是在 main 而不是另一个类中进行的
one class should invoke method of another class using a function pointer - 我无法遵循已接受的答案,因为我不清楚如何使用 <functional> 标头。
我有一个 Useful Function 类 UF,我在其中声明并定义了我的程序的所有常用实用程序函数。这些功能之一是
int UF::compar_dbl_asc(const void *a, const void *b)//comparator for sorting
{ //array of double in ascending order
int aa = *((int *)a), bb = *((int *)b);
if (base_arr_dbl[aa] < base_arr_dbl[bb])
return -1;
if (base_arr_dbl[aa] == base_arr_dbl[bb])
return 0;
if (base_arr_dbl[aa] > base_arr_dbl[bb])
return 1;
}
这是我打算在qsort() 中使用的比较器函数,用于按升序对双精度数进行排序。
在UF 类定义中,我也有double* base_arr_dbl; 作为声明。这是 qsort 将使用的值数组(双精度)。
现在,在我的另一个名为SEP 的类中,我有一个函数fn1,其中我想让base_arr_dbl 指向一个本地(到fn1)双数组,我想使用UF 中的比较器函数调用qsort。具体来说,虽然这可能不是必需的,但我不对实际值的数组进行排序,而是对索引数组sortedindices[] 进行排序,这样sortedindices[0] 将保存base_arr_dbl[] 数组中最小条目的索引.即排序顺序为base_arr_dbl[sortedindices[0]], base_arr_dbl[sortedindices[1]]等
所以,我这样做:
void SEP::fn1(UF *uf) {
double ratio[100];
//populate ratio's entries
//Now, sort ratio's entries.
uf->set_base_arr_dbl(ratio); //This function is defined as
//void UF::set_base_arr_dbl(double *ptr) { base_arr_dbl = ptr; }
qsort(sortedindices, 100, sizeof(double), uf->compar_dbl_asc);
}
但是,qsort(sortedindices, 100, sizeof(double), uf->compar_dbl_asc); 行会引发以下编译时错误:
error C3867: 'USEFUL_FUNCTIONS::compar_dbl_asc': non-standard syntax; use '&' to create a pointer to member
我尝试使用 &uf->compar_dbl_asc 但这给出了错误:
error C2276: '&': illegal operation on bound member function expression
感谢任何帮助解决此问题的方法。
【问题讨论】:
-
“我有一个有用的函数类,UF,我在其中为我的程序声明并定义了所有常见的实用函数”这听起来像一个可怕的设计
-
为什么不用命名空间呢?你的实用程序函数需要状态吗?
-
否则,这些实用函数不能在类中使用
static,这样您就不需要实例了吗? -
@AndyG 我不知道函数需要状态意味着什么。你能详细说明一下吗?另外,这是否有助于解决这个函数指针问题?
-
@Tryer:我的意思是成员变量。
UF是否有成员变量,如果有,为什么?似乎您有一个应该首先解决的设计问题。我们可以帮助您编写理论上适用于这种设计的代码,但它会鼓励不良的设计原则。
标签: c++ function-pointers