鍍金池/ 問答/C++/ 類成員函數(shù)的指針問題:pf = base::print; 和 pf = &amp

類成員函數(shù)的指針問題: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.使用語句一和語句二輸出結(jié)果相同,均為:In devired; 請問為什么?
3.使用語句一pf = base::print時,CLION提示Function 'print' must be static., 是CLION有問題么?

回答
編輯回答
終相守

輸出結(jié)果相同是因為pf指向同一個函數(shù),為"In devired"是因為pf指向虛函數(shù)。

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.

取非靜態(tài)成員函數(shù)的地址必須加&。不是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. 這兩部分歷代標(biāo)準(zhǔn)應(yīng)該都一樣,不放心的話自己根據(jù)編譯器設(shè)置查閱相關(guān)文檔吧。

2018年3月20日 03:30