指向基类错误的成员函数的指针

时间:2013-04-04 07:03:02

标签: c++ pointers function-pointers member-function-pointers

有人可以帮我辨别我哪里错了吗?我正在尝试使用函数指针到基类函数

错误C2064:术语不评估为在行号30上取0参数的函数,即*(app)()

#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
#include<typeinfo>

using namespace std;

class A{
public:
    int a(){
        printf("A");
        return 0;
    }
};

class B : public A{
public:
    int b(){
        printf("B");
        return 0;
    }
};

class C : public B{
public:
    int(C::*app)();
    int c(){
        app =&C::a;
        printf("%s",typeid(app).name());
        *(app)();
        printf("C");
        return 0;
    }
};
int main(){
    C *obj = new C();
    obj->c();
    getch();
}

4 个答案:

答案 0 :(得分:3)

在调用指向成员函数的指针时,必须使用。*或 - &gt; *

    class C : public B{
    public:
        int(C::*app)();
        int c(){
            app =&C::a;
            printf("%s",typeid(app).name());
            (this->*app)(); // use ->* operator within ()
            printf("C");
            return 0;
        }
    };

答案 1 :(得分:2)

指向成员的指针必须始终与对象的指针/引用结合使用。你可能想写这个:

(this->*app)();

答案 2 :(得分:1)

http://msdn.microsoft.com/en-us/library/k8336763.aspx

  

二元运算符 - &gt; *组合了它的第一个操作数,它必须是a   指向类类型对象的指针,带有第二个操作数,即   必须是指向成员的指针类型。

所以这将解决你的问题:

class C : public B {
    public:
        int(C::*app)();

        int c() {
            app = &C::a;
            printf("%s", typeid(app).name());
            (this->*app)();
            printf("C");
            return 0;
        }
};

答案 3 :(得分:0)

我有一个预感,你真正试图解决的问题是“如何从派生类中调用基类函数?”如果是这种情况,答案是:

int c(){
    app =&C::a;
    printf("%s",typeid(app).name());
    A::a(); //A:: scopes the function that's being called
    printf("C");
    return 0;
}

int c(){
    app =&C::a;
    printf("%s",typeid(app).name());
    this->a();
    printf("C");
    return 0;
}
相关问题