小编Ruf*_*fus的帖子

类成员函数作为函数指针

我有一个类,其成员函数之一实际上是一个函数指针.这样,用户可以覆盖此功能的功能.遗憾的是,我在运行此功能时遇到了一些困难 我用g ++编译.

以下是代码:

    #include <iostream>

    using namespace std;

    double fcn_mod(const double &phit){
        return 1.2+phit;
    }

    class Object{
        public:
            Object() {
                fcn_ptr = (double (*)(const double &)) &Object::fcn_default;
            }
            double (*fcn_ptr)(const double &) = NULL;

        private:
            double fcn_default(const double &phit){
                return 3.2+phit;
            }
    };


    int main(){

        Object test1,test2;

        cout << (test1.*fcn_ptr)(2) << endl; // can not compile here

        test2.fcn_ptr = &fcn_mod;
        cout << (test2.*fcn_ptr)(2) << endl; // and here

        cout << "test" << endl;
    }
Run Code Online (Sandbox Code Playgroud)

错误消息是:

    erreur: ‘fcn_ptr’ was not …
Run Code Online (Sandbox Code Playgroud)

c++ function-pointers class member-functions

0
推荐指数
1
解决办法
170
查看次数

标签 统计

c++ ×1

class ×1

function-pointers ×1

member-functions ×1