2014-04-07 158 views
0

为什么the following code无法正常工作?为什么派生类不能访问基类静态方法?

class A 
{ 
    static void Method() { std::cout << "method called."; } 
}; 

class B : public A 
{ 
    // Has a bunch of stuff but not "Method" 
}; 

int main() 
{ 
    B::Method(); 
} 

我知道我可以使它通过添加以下到B的工作,但是这将是很好,如果这是没有必要的,尤其是如果有从A派生几类

static void Method() { A::Method(); } 
+1

@jthill你是对的。如果它是公开的,它工作得很好。谢谢。 – sgryzko

回答

4

默认情况下,使用class密钥声明的类的成员是私有的。为了让它们公开,你必须说:

class A 
{ 
    public: 
// ^^^^^^^ 
     static void Method() { cout << "method called."; } 
}; 
+0

我的问题已被编辑。即使明确公开,我仍然无法访问此方法。 – sgryzko

+0

你的意思是在'main'中调用'B :: Method'而不是'derived :: Method' – vogomatix

+0

@SteveJessop你说得对。我的错。错误已被修复。 – sgryzko

相关问题