在C ++中调用对象上特定类的虚函数

时间:2013-04-27 14:29:35

标签: c++

我需要从类外部的某个对象上调用“声明”类型的函数。我做了一个小代码示例,并将所需的行为作为注释,因为我不知道如何问这个:)

template<typename T>
void hun(T* obj, class C* c)
{
    //do some checking on c
    if(some conditions from c are true)
    {
        //call fun from T ignoring it's virtual
    }
}

struct A
{
    virtual void fun(){};
    virtual void gun(class C* c)
    {
        //do something specific to A
        hun(this, c); //here call fun from A even if real type of this is B
    };
}

struct B : public A
{
    void fun(){};
    void gun(class C* c)
    {
        //do something specific to B
        hun(this, c);//here call fun from B even if real type of this is something derived from B
    };
}

有可能实现这种行为吗?

我知道我可以使用fun()A::fun()从课堂内拨打B::fun(),但来自hun()的检查对所有课程都很常见,我不想要使用此代码污染gun()

1 个答案:

答案 0 :(得分:9)

(这可能已经在其他地方得到了回答..)

您可以使用qualified-id显式调用虚拟函数的一个覆盖。成员函数的限定id的格式为my_class::my_function

供参考,参见C ++ Standard [expr.call] / 1:

  

如果所选函数是非虚拟的,或者类中的id-expression   成员访问表达式是一个qualified-id,该函数被调用。否则,它的最终覆盖(10.3)   调用对象表达式的动态类型。

实施例

template<typename T>
void hun(T* obj, class C* c)
{
    //do some checking on c
    if(some conditions from c are true)
    {
        //call fun from T ignoring it's virtual
        obj->T::fun(); // T::fun is a qualified-id
    }
}

struct A
{
    virtual void fun(){};
    virtual void gun(class C* c)
    {
        //do something specific to A
        hun(this, c); //here call fun from A even if real type of this is B
    };
}; // note: semicolon was missing

struct B : public A
{
    void fun(){};
    void gun(class C* c)
    {
        //do something specific to B
        hun(this, c);//here call fun from B even if real type of this is something derived from B
    };
};
相关问题