C ++如何使函数指针指向类方法 [英] C++ How to make function pointer to class method

查看:129
本文介绍了C ++如何使函数指针指向类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在制作指向类方法的函数指针时遇到麻烦.我做了一个指向非类方法的函数指针,它工作正常.

I'm having trouble making a function pointer to a class method. I made a function pointer to a non-class method and it works fine.

int foo(){
    return 5;
}

 int main()
{
    int (*pointer)() = foo;

    std::cout << pointer();

    return 0;
}

我试图将其应用为使类中的实例变量成为函数指针.

I tried to apply this to have an instance variable in a class be a function pointer.

这是头文件.它声明了变量方法将指向的私有方法Print.

This is the header file. It declares the private method Print which the variable method will point to.

class Game
{

public:

    Game();

private:

    void Print();

    void (method)( void );

};

Game构造函数尝试将指针方法分配给Print方法的地址.编译后,该行出现错误,提示错误:必须调用对非静态成员函数的引用;".我不知道那是什么意思什么是实现此目的的正确方法?

The Game constructor attempts to assign the pointer method to the address of the Print method. Upon compile, an error comes up at that line saying "error: reference to non-static member function must be called;". I don't know what that means. Whats the correct way of implementing this?

Game::Game( void )
{

    method = &Game::Print;

}

void Game::Print(){
    std::cout << "PRINT";
}

推荐答案

成员函数与普通函数有很多不同,因此当您要指向成员函数时,需要一个指向成员函数的指针,而不仅仅是指向功能的指针.指向成员函数的指针的语法包括成员函数是其成员的类:

A member function is quite a bit different from an ordinary function, so when you want to point to a member function you need a pointer-to-member-function, not a mere pointer-to-function. The syntax for a pointer-to-member-function includes the class that the member function is a member of:

void (Game::*mptr)();

这定义了一个名为mptr的成员函数指针,该函数持有一个指向Games类的成员函数的指针,该成员函数不带参数也不返回任何内容.将其与普通的函数指针进行对比:

This defines a pointer-to-member-function named mptr that holds a pointer to a member function of the class Games that takes no arguments and returns nothing. Contrast that with an ordinary function pointer:

void (*ptr)();

这定义了一个指向函数ptr的指针,该指针持有一个不带任何参数且不返回任何内容的函数的指针.

This defined a pointer-to-function named ptr that holds a pointer to a function that takes no arguments and returns nothing.

这篇关于C ++如何使函数指针指向类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆