我试图通过允许我选择不同形式的数学函数并通过将它们实例化为特定类的对象来改变它们的参数,来在数字中实现更大的灵活性。该课程包括一些我可以选择的数学函数以及一些可以改变的参数。类的构造函数根据我想要的数学函数将类中的成员函数指针设置为成员函数。我想只使用指针直接通过在例程中使用指针来调用它指向的任何函数。
但是,事实证明这令人望而生畏,因为我不知道成员函数指针需要某种语法,并且根据我所收集的内容,其工作原理与常规函数指针有些不同。我已经做了很多实验,并为自己构建了一个下面共享的最小示例。
#include<iostream>
#include<string.h>
#include<cstdlib>
#include<stdio.h>
class Someclass
{
public:
// constructor to set pointer
Someclass(std::string);
// member function pointer to hold functions
void (Someclass::*fptr)();
// auxiliary function to call testfunction via pointer
void call ();
// testfunction
void foo();
};
// testfunction
void Someclass::foo()
{
printf("foo says hi! \n");
}
// call via specific function
void Someclass::call()
{
(this->*fptr)();
}
// constructor
Someclass::Someclass(std::string name)
{
if(name=="foo")
{
this->fptr = &Someclass::foo;
}
}
int main()
{
Someclass someobject("foo");
someobject.foo(); // direct testfunction call: Works OK
someobject.call(); // call via auxiliary function: Works OK
//(someobject.*fptr)(); // direct pointer dereferencing: Gives Error
return(EXIT_SUCCESS);
}
它显示了我可以通过使用另一个成员函数访问该指针,该成员函数仅通过使用this指针调用该指针指向的内容。但是,如果尝试通过该行直接在主函数中使用指针,我似乎仍然无法使函数调用正常工作,
(someobject.*fptr)()
这个特定的表达式导致我的编译器抱怨范围,如果我包括类范围,则编译器会提及对非静态成员的无效使用。不过,对于为什么我的实现在这里不起作用以及是否起作用,我的问题中的正确语法如何以及为什么必须如此,我仍然感到困惑。
任何见解将不胜感激。
这样做的原因是.*
指示指向成员函数的指针,而不像.
and.->
操作符那样直接引用对象的成员。由于fptr
是成员Someclass
而不是局部变量,因此您需要像这样直接引用它
(someobject.*someobject.fptr)();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句