Zeiger auf Elementfunktionen



  • Hey Leute,

    Wie erstelle ich einen Funktionszeiger auf eine Methode welche in einer Klasse
    deklariert ist?





  • hm hab das jez so gemacht:

    #include <fstream>
    
    class A {
    private:
      void test1() { printf("A::1\n"); };
      void test2() { printf("A::2\n"); };
    public:
    	typedef void (*A::A_f)();
     A_f test;
     void exec(int i);
    };
    
    void A::exec(int i) {
     switch(i) {
      case 1:
       test = &test1;
       break;
     case 2:
       test = &test2;
       break;
     }
    }
    
    int main( int argc, char **argv ) {
    	A a;
    
    	a.exec(1);
    	a.exec(2);
    
    	return 0;
    
    }
    }
    

    //funktioniert aber irgendwie nicht >>
    error C2276: '&' : illegal operation on bound member function expression
    error C2276: '&' : illegal operation on bound member function expression
    beides bei den Zuweisungen von test



  • _carnage schrieb:

    ...
       typedef void (*A::A_f)();
    ...
       test = &test1;
    ...
    
    ...
       typedef void (A::*A_f)();
    ...
       test = &A::test1;
    ...
    

    🙂



  • und wenn ich test() aufrufe sagt der Compiler aber:
    "error C2064: term does not evaluate to a function"

    was heisst das?



  • #include <string>
    
    struct foo
    {
    	typedef void ( foo::*fun_ptr )() const;
    
    private:
    	void test1() const { std::cout << "foo::test1()" << std::endl; }
    	void test2() const { std::cout << "foo::test2()" << std::endl; }
    
    public:
    	void exec( unsigned index )
    	{
    		assert( index < 2 );
    
    		static fun_ptr functions[] =
    		{
    			&foo::test1,
    			&foo::test2
    		};
    
    		( *this.*functions[ index ] )();
    	}
    };
    
    int main()
    {
    	foo bar;
    
    	bar.exec( 0 );
    	bar.exec( 1 );
    
    	std::cin.get();
    }
    

    Bei Methodenfunktionszeigern brauchst du natürlich auch eine gültige Instanz.


Anmelden zum Antworten