对单例对象c++使用函数指针

Using function pointers with singleton objects c++

本文关键字:函数 指针 c++ 单例 对象      更新时间:2023-10-16

我是c++新手,试着在谷歌上搜索并找到答案,但没有成功。很可能这应该是个愚蠢的问题。

我总是很难理解函数指针及其语法。

这是我第一次在一些严肃的代码中使用它。

我有一个singleton类,如下所示。未显示Singleton方法。

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()以及如何通过singleton对象调用它。我尝试了不同的选项,甚至无法编译这个。我有很多错误,如果需要,我会公布这些细节。我过得很艰难。如果有重复的话,有人能帮忙或指出吗?如果有,我会删除这篇文章。

谢谢。

我想你正在寻找这个:

class Derived: public base
{
    int fn(int (base::*arg)(unsigned int));
};

fn中,您可以这样使用arg

return (this->*arg)(7);

语法int (base::*p)(unsigned int)创建一个指向成员函数的指针您将它与指向对象的指针(或引用)一起使用,以调用成员函数。若要取消引用指针,请将->*与指向对象的指针一起使用,或将.*与对象本身一起使用。

您可以将基类的指针作为参数发送到fn()。你为什么不也发布错误消息呢?

您的意思是指向成员函数的指针吗?然后尝试:(在注释中更正)。您需要一个基本对象来调用fp-

typedef double (base::*bfptr)(double);
int fn(bfptr fp);