Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

child class method pointer to method parent argument c++

it might be strange what i'm trying to see and i will try to clarify as much as possible. I'm using gcc 4.8 on ubuntu 14.04 and C++11.

What i want trying to do is:

  • make a class A
  • make a function in that class A which gets as argument
  • a pointer to a class member of the same class
  • make a new class B which inherits from A
  • make a new method of class B
  • give a pointer to that method of class B to a method of parentclass A as argument

    class A{
        typedef void(A::*METHOD);        
    
        void executeMethod(METHOD arg){};
    }
    
    class B : A{
    
        void sampleMethod(){};
    
        void childMethod(){              
    
          this->executeMethod(&B::sampleMethod); //<== error
        }
    }
    

However this brings me the following error in codeblocks:

error: no matching function to call for 'B::executeMethod(void B::*)'

Is there any way around this? Is there anything else i need to do to make it clear to you, what i'm trying to accomplish?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that sampleMethod isn't a member of A, it's a member of B and can't convert to a void(A::*).

Did you consider using virtual methods perhaps?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...