在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

類成員函數(shù)的指針問(wèn)題:pf = base::print; 和 pf = &base::print;等價(jià)么?

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; //語(yǔ)句一
    //pf = &base::print; // 語(yǔ)句二
    display(pb, pf);
}

2.使用語(yǔ)句一和語(yǔ)句二輸出結(jié)果相同,均為:In devired; 請(qǐng)問(wèn)為什么?
3.使用語(yǔ)句一pf = base::print時(shí),CLION提示Function 'print' must be static., 是CLION有問(wèn)題么?

回答
編輯回答
終相守

輸出結(jié)果相同是因?yàn)閜f指向同一個(gè)函數(shù),為"In devired"是因?yàn)閜f指向虛函數(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的問(wèn)題。

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