类成员函数的指针问题:pf = base::print; 和 pf = &base::print;等价么?

1.有代码如下:

#include <iostream>
using  namespace std;

class base {
public:
    int a = 10;
    virtual void print() { cout << "In Base" << endl;}
};

class derived : public base {
public:
    void print() { cout << " In devired" << endl;}
};
void display(base *pb, void(base::*pf)()) { (pb->*pf)();}

int main() {
    derived d;
    base *pb = &d;
    void (base :: *pf)();
    pf = base::print; //语句一
    //pf = &base::print; // 语句二
    display(pb, pf);
}

2.使用语句一和语句二输出结果相同,均为:In devired; 请问为什么?
3.使用语句一pf = base::print时,CLION提示Function 'print' must be static., 是CLION有问题么?

阅读 1.8k
1 个回答

输出结果相同是因为pf指向同一个函数,为"In devired"是因为pf指向虚函数。

8.5.1.2.2 For a call to a non-static member function, the postfix expression shall be an implicit (12.2.2, 12.2.3) or explicit class member access (8.5.1.5) whose id-expression is a function member name, or a pointer-to-member expression (8.5.4) selecting a function member;

8.5.1.2.3 If a function or member function name is used, the appropriate function and the validity of the call are determined according to the rules in 16.3. If the selected function is non-virtual, or if the id-expression in the class member access expression is a qualified-id, that function is called. Otherwise, its final overrider (13.3) in the dynamic type of the object expression is called; such a call is referred to as a virtual function call.

取非静态成员函数的地址必须加&。不是CLION的问题。

8.5.2.1.4 A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses.

引自N4741, C++20 working draft. 这两部分历代标准应该都一样,不放心的话自己根据编译器设置查阅相关文档吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏