我是 C++ 新手,尝试通过谷歌搜索和搜索寻找答案,但无济于事。这很可能是个愚蠢的问题。
我总是难以理解函数指针及其语法。
这是我第一次在一些严肃的代码中使用它。
我有一个像这样的单例类。未显示单例方法。
class Derived:public base
{
int fn();
// This function has a single argument which
// is function pointer to any of the base class
// function having same argument/return type of
// the singleton object.
};
class base
{
public:
int ConvertIntIndex(const unsigned int Index);
int ConvertStringIndex(const unsigned int Index);
int ConvertOidIndex(const unsigned int Index);
}
如何声明 fn()
以及如何通过单例对象调用它。我尝试了不同的选项,甚至无法编译它。我收到了很多错误,如果需要会发布这些详细信息。我过得很艰难。如果存在,任何人都可以帮助或指出重复项吗?如果有的话,我会删除这个帖子。
谢谢。
最佳答案
我猜你正在寻找这个:
class Derived: public base
{
int fn(int (base::*arg)(unsigned int));
};
在 fn
中,您可以像这样使用 arg
:
return (this->*arg)(7);
int (base::*p)(unsigned int)
语法创建了一个指向成员函数的指针。您可以将它与一个指向对象调用成员函数。要取消引用指针,请将 ->*
与指向对象的指针一起使用,或将 .*
与对象本身一起使用。
关于c++ - 将函数指针与单例对象一起使用 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707190/