c++ - 将函数指针与单例对象一起使用 C++

标签 c++ singleton function-pointers

我是 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/

相关文章:

c++ - 如何在 C/C++ 中使用 FFmpeg API 覆盖过滤器

objective-c - 为什么从sharedInstance返回id

javascript - 如何从其中的另一个对象访问单例中的 'private functions'

c++ - 将指向成员函数的指针转换为 intptr_t

c++ - 带函数指针的模板推导还原

c++ - 我们如何生成一定数量的随机数并将它们相互链接,而无需将数字链接到自身?

c++ - b2BlockAllocator.cpp 中的 Box2D 崩溃

c++ - 如何以编程方式将工具按钮移动到右侧工具栏区域?

java - 在多线程环境中访问大型单例对象

C编程,错误: called object is not a function or function pointer