繁体   English   中英

C ++中的类成员函数指针

[英]Class member function pointers in C++

我想在一个对象上调用另一个类的成员函数,但是我似乎无法弄清楚它是如何工作的。 作为示例代码,说明如何工作:

Class A {
  void somefunction(int x);
}

Class B : A {
  void someotherfunction(int x);
}

Class C {
  void x() {
      callY(&ofthefunction); 
}   //here you call the function, you dont have an object yet,    and you don't know the argument yet, this will be found in function callY

  void Y(*thefunction) {
       find int x;
       if(something)
             A a = find a;
             a->thefunction(x);
       else 
             B b = find b;
             b->thefunction(x);
}
}

我希望这很有道理,也可以将其拆分为2种方法,Y1和Y2,但是看到90%的代码是相同的(在XML文件中查找内容),只有对象和参数将其保存在哪里是不同的,我想这样做

您可以使用称为虚函数的东西。 顺便说一句,你的语法是可怕的,它的classClass ,你需要花括号为您的条件语句,和明智的应用程序public ,一些额外的分号等,如果你会去附近的编译器来这里,Y之前,我们将不胜感激'知道。

class A {
public:
  virtual void somefunction(int x);
};

class B : public A {
public:
  virtual void somefunction(int x);
};

void func(A& a) {
    int x = 0;
    // Do something to find x
    a.somefunction(x); 
    // calls A::somefunction if this refers to an A
    // or B::somefunction if it's a B
}
int main() {
    A a;
    func(a); // calls A::somefunction
    B b;
    func(b); // calls B::somefunction
}

可以做些什么,尽管我不会这样解决:

class A {
public:
    virtual int doit(int x) { return x+1; }
};

class B : public A {
public:
    int doit2(int x) { return x*3; }
    int doit(int x) { return x*2; }
};

int foo(int (A::*func)(int), int x, bool usea) {
    if (usea) {
        A a;
        return (a.*func)(x);
    } else {
        B b;
        return (b.*func)(x);
    }
}

int main() {
    int (A::*bla)(int) = &A::doit;
    foo(bla, 3, true);
    foo(bla, 3, false);

}

但是,要使其正常工作,必须满足以下条件:

  1. 您必须使用基类的函数指针(例如int (A::*bla)(int) ),否则您将无法在该基类上调用它(例如int (B::*bla)(int)仅可用于B实例,而不能用于A实例,即使该方法已在A )中定义。
  2. 这些方法必须与基类中的名称相同
  3. 要使用覆盖(例如,派生类中的不同impl),您必须使用virtual函数。

但是我宁愿重新考虑您的设计...

不,那根本行不通。 指向A成员的指针将始终指向该函数,即使在B上调用它也是如此,因为B继承自A。

您需要使用虚函数。 我看到DeadMG击败了我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM