C++ 友元函数的函数指针

成员函数的指针

讲友元之前先讲普通的成员函数的函数指针

class Std_interface {
public:
    virtual void suspend() = 0;
};

// define the pointer of function
typedef void (Std_interface::* Pstd_mem) ()

void f(Std_interface* p) {
    Pstd_mem s = &Std_interface::suspend;

    // call directly
    p->suspend();

    // by pointer
    (p->*s)();
}

当函数指针指向类成员对象时,对函数指针的定义必须加上类名以及::(作用域运算符)标识该函数指针指向哪个类的成员函数。

调用函数指针所指向的类成员函数时,必须提供函数所操作的类对象,类似于成员函数的访问,用这个对象去调用这个函数。

友元函数

那么,如果我们的函数指针已经声明成普通的函数指针,那么有无解决方案?使用友元函数,与static 函数相同的特性是:

  1. 毋须提供一个this指针去激活该函数
  2. 可以访问类的私有成员

不同之处在于该函数不处于该类的作用域之中!分析如下代码:

// GlAnimator.h
class GlAnimator {
public:
    int example();
    friend int LoopInThread(GlAnimator *animator_ptr);
};

// GlAnimator.cpp
typedef int(*InnerLoop)(GlAnimator *);

int GlAnimator::example() {
    InnerLoop inner_loop = &LoopInThread;
    return 0;
}
// friend function
int LoopInThread(GlAnimator *animator_ptr) {
    // ...
    return 0;
}

InnerLoop inner_loop = &LoopInThread; 处是会报错的,说"LoopInThread undeclared" 这个很有意思了,明明在头文件定义了的!原因是上面提到的其作用域不在该类内,而我偏偏在成员函数example()里面去取其地址,那么显然就是没有声明的了。

解决方案就是重新声明一遍,一共声明两遍,在取函数指针前声明即可,我喜欢在头文件里做,头文件修改如下:

// GlAnimator.h
class GlAnimator {
public:
    int example();
    friend int LoopInThread(GlAnimator *animator_ptr);
};

// declare the friend function again
int LoopInThread(GlAnimator *animator_ptr);

参考资料

http://www.cplusplus.com/forum/general/23265/

http://hipercomer.blog.51cto.com/4415661/941682

原文地址:https://www.cnblogs.com/psklf/p/6490172.html