2014-09-25 28 views
0

我試圖運行此代碼,但無法理解導致錯誤的原因。'*'標記之前的預期非限定標識:指向成員函數的指針

#include <iostream> 
using namespace std; 

class Shape 
{ 
    public: 
     void show (float) { cout << "Hello"; } 
}; 

int main () 
{ 

    void (Shape::*FPtr2) (float) = &Shape :: show; 
    (Shape::*FPtr2)(1.1); 

    return 0; 
} 
+2

要調用'show',你需要一個'Shape' *對象*。 – 2014-09-25 21:08:10

回答

2

調用非靜態成員函數需要一個對象。通過指向成員函數調用非靜態成員函數也需要一個對象。

#include <iostream> 
using namespace std; 

class Shape 
{ 
    public: 
     void show (float) { cout << "Hello"; } 
}; 

int main () 
{ 
    void (Shape::*FPtr2) (float) = &Shape :: show; 
    Shape myShape; // here is my object 
    (myShape.*FPtr2)(1.1); // here is the call to the object's show function via pointer 
    return 0; 
}