2010-03-08 4 views
53

같은 클래스의 다른 함수를 가리키는 포인터의 클래스 멤버로 함수 포인터를 설정하고 싶습니다. 내가 이것을하는 이유는 복잡합니다.함수 포인터가 멤버 함수

이 예에서

, I 출력이 "1"

class A { 
public: 
int f(); 
int (*x)(); 
} 

int A::f() { 
return 1; 
} 


int main() { 
A a; 
a.x = a.f; 
printf("%d\n",a.x()) 
} 

싶습니다 그러나 이것은 컴파일에 실패합니다. 왜?

답변

89

구문이 잘못되었습니다. 멤버 포인터는 일반 포인터와 다른 유형 범주입니다. 멤버 포인터는 클래스의 객체와 함께 사용되어야 할 것이다 :

class A { 
public: 
int f(); 
int (A::*x)(); // <- declare by saying what class it is a pointer to 
}; 

int A::f() { 
return 1; 
} 


int main() { 
A a; 
a.x = &A::f; // use the :: syntax 
printf("%d\n",(a.*(a.x))()); // use together with an object of its class 
} 

a.x

아직 함수가 호출하는 객체 무슨 말을하지 않습니다. 단지 객체 a에 저장된 포인터를 사용하고 싶다고 말합니다. 다른 연산자로 a을 붙이면 .* 연산자에 대한 왼쪽 피연산자는 함수를 호출 할 객체를 컴파일러에게 알려줍니다.

+0

나는 이것이 오래되었다는 것을 알고 있지만'(a. * a.x)() '의 사용법을 이해하지 못한다. 왜 '(a. * x)()'가 작동하지 않습니까? –

+0

@gau는 x가 범위에 없기 때문에 –

+1

@gau 내가 명확하게하기 위해 지금 괄호를 추가했습니다. –

8

함수에 대한 포인터뿐만 아니라 멤버 함수에 대한 포인터를 사용해야합니다.

class A { 
    int f() { return 1; } 
public: 
    int (A::*x)(); 

    A() : x(&A::f) {} 
}; 

int main() { 
    A a; 
    std::cout << (a.*a.x)(); 
    return 0; 
} 
15

int (*x)()은 멤버 함수에 대한 포인터가 아닙니다. 멤버 함수에 대한 포인터는 다음과 같이 작성됩니다 : int (A::*x)(void) = &A::f;.

5

Call member function on string command

#include <iostream> 
#include <string> 


class A 
{ 
public: 
    void call(); 
private: 
    void printH(); 
    void command(std::string a, std::string b, void (A::*func)()); 
}; 

void A::printH() 
{ 
    std::cout<< "H\n"; 
} 

void A::call() 
{ 
    command("a","a", &A::printH); 
} 

void A::command(std::string a, std::string b, void (A::*func)()) 
{ 
    if(a == b) 
    { 
     (this->*func)(); 
    } 
} 

int main() 
{ 
    A a; 
    a.call(); 
    return 0; 
} 

지불 (this->*func)();에 대한 관심이 다른 곳이 페이지의 스털링 답변을 기반으로하지만 클래스 이름 void (A::*func)()

0

와 함수 포인터를 선언하는 방법, 내가 사용 사례가 있었다 그것은 그들에 의해 완전히 해결되지 않았다. 함수 포인터의 벡터에 대해 다음을 수행하십시오 당신이 매개 변수 구문 도움 팁 등 아마도 유용와 결혼 할 필요가 인덱스 기능으로 명령 인터프리터를 작성하는 경우이 같은

#include <iostream> 
#include <vector> 
#include <stdio.h> 
#include <stdlib.h> 

class A{ 
public: 
    typedef vector<int> (A::*AFunc)(int I1,int I2); 
    vector<AFunc> FuncList; 
    inline int Subtract(int I1,int I2){return I1-I2;}; 
    inline int Add(int I1,int I2){return I1+I2;}; 
    ... 
    void Populate(); 
    void ExecuteAll(); 
}; 

void A::Populate(){ 
    FuncList.push_back(&A::Subtract); 
    FuncList.push_back(&A::Add); 
    ... 
} 

void A::ExecuteAll(){ 
    int In1=1,In2=2,Out=0; 
    for(size_t FuncId=0;FuncId<FuncList.size();FuncId++){ 
    Out=(this->*FuncList[FuncId])(In1,In2); 
    printf("Function %ld output %d\n",FuncId,Out); 
    } 
} 

int main(){ 
    A Demo; 
    Demo.Populate(); 
    Demo.ExecuteAll(); 
    return 0; 
} 

뭔가 유용 메뉴에서.