【问题标题】:Initializing array of structures with function pointer member in C++在 C++ 中使用函数指针成员初始化结构数组
【发布时间】:2015-06-18 05:38:37
【问题描述】:

我在初始化一个以函数指针作为成员的结构数组时遇到了麻烦。

class Record
{
    private:
    typedef void (*display_fn_t) ();
    struct record {
        int a;
        display_fn_t disp;
    };
    static const record rec[];

    void disp1() { cout << "Display 1 with a string to display" << endl; }
    void disp2() { cout << "Display 2 with an integer to display" << endl; }

    public:
    int find() { /* logic to find the record comes here */ }
    void display() {
        for (int i = 0; i < 2; i++) {
            rec[i].disp();
        }
    }
}

const Record::record Record::rec[] = {
    { 10, disp1 },
    { 11, disp2 }
};

int main()
{
    Record r;
    if (r.find())
        r.display();
    return 0;
}

当我编译上面的代码时,我得到以下编译错误:

mca_record.cpp:56:错误:类型为“void (Record::)()”的参数确实 不匹配‘void (*)()’

【问题讨论】:

  • 指向成员函数的指针与指向非成员函数的指针相同。 SO上必须有数百甚至数千个重复项。问题是指向成员函数的指针需要调用实际的对象实例,而指向非成员函数的指针则不需要。
  • 另外,您可能想了解std::functionstd::bind
  • 另外,缺少分号。

标签: c++ arrays function-pointers


【解决方案1】:

您的语法错误并且没有使用适当的运算符。

修复大量语法错误,去除不相关的find 操作,然后利用适当的成员函数指针和operator -&gt;* 给出以下(执行此操作的几种方法之一):

#include <iostream>

class Record
{
private:
    typedef void (Record::*display_memfn_t)();
    struct record
    {
        int a;
        display_memfn_t disp;
    };

    static const record rec[];

    void disp1() { std::cout << "Display 1 with a string to display" << std::endl; }
    void disp2() { std::cout << "Display 2 with an integer to display" << std::endl; }

public:
    void display();
};

const Record::record Record::rec[] =
{
    { 10, &Record::disp1 },
    { 11, &Record::disp2 }
};

void Record::display()
{
    for (size_t i=0; i<sizeof rec/sizeof*rec; ++i)
        (this->*(rec[i].disp))();
}

int main()
{
    Record r;
    r.display();
    return 0;
}

输出

Display 1 with a string to display
Display 2 with an integer to display

将其与您现有的代码进行比较,尤其是指向成员函数的指针不仅仅是指向函数的指针。它们需要不同的处理方式和通常不同的操作员来使用。 See here 用于不同的成员访问方法(变量和函数)。

祝你好运。

【讨论】:

  • 谢谢@WhozCraig。我需要 find 函数,因为有一些逻辑可以获取一些在显示函数中使用的值。但是,我可以利用您提到的一些调整。这真的很酷。
【解决方案2】:

要使调用生效,您必须像这样调用它:

        for (int i = 0; i < 2; i++) {
            (*rec[i].disp)();
        }

并以这种方式初始化表:

const Record::record Record::rec[] = {
    { 10, &Record::disp1 },
    { 11, &Record::disp2 }
};

【讨论】:

  • 仔细观察,@WhozCraig 已经解决了我的问题。但是 +1 用于您直接攻击问题陈述的简短描述。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多