实例方法称为静态方法

时间:2012-07-25 20:23:24

标签: c++

为什么B :: Func可以使用使其看起来像静态方法调用的语法来调用A :: Func?这不应该失败,因为它是一个实例方法吗?

class A {
public:
    void Func() { 
        printf( "test" );
    }
};

class B : private A {
public:
    void Func() {
        A::Func();  // why does it work? (look below in main())
    }
};

int main() {
    B obj;

    obj.Func();
    // but we cannot write here, because it's not static
    // A::Func();

    return 0;
}

1 个答案:

答案 0 :(得分:5)

这不是“被称为静态”。这仅仅是用于显式指定要调用的成员函数的语法。即使Func是虚拟的,也可以使用该语法来调用基类版本。

class B : public A {
public:
    void Func() {
        this->A::Func(); /* this-> can be omitted */
    }
};

int main() {
    B obj;
    obj.A::Func();
    return 0;
}

编辑:obj.A::Func()实际上在您的情况下无效,因为继承是私有的,因此main无法看到AB的基础。我已将B的继承更改为公开以使答案正确,但在friend函数中,它仍然可以在类之外工作。

相关问题