2012-07-25 87 views
0

为什么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; 
} 

回答

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函数中,它仍然可以在课程之外使用。