派生类拒绝访问基类受保护的成员 [英] Derived class denied access to base class protected members
问题描述
考虑以下课程:
类基数
{
受保护:
  int m_id;
};
class派生:公共基地
{
公开:
  static bool Foo()
  {
      return offsetof(Base,m_id)> 0;
  }
};
Consider the following classes:
class Base
{
protected:
int m_id;
};
class Derived : public Base
{
public:
static bool Foo()
{
return offsetof(Base, m_id) > 0;
}
};
此代码无法编译。 Visual Studio 2015抱怨静态派生的"Foo"功能。
错误C2248:'Base :: m_id':无法访问"Base"类中声明的受保护成员
\ consoleapplication1.cpp(83):注意:请参阅'Base :: m_id'的声明。
这对我没有意义。 我在派生类的静态成员函数中。 它是否应该无法引用基类的受保护成员?
This code does not compile. Visual Studio 2015 complains about the static, derived "Foo" function.
error C2248: 'Base::m_id': cannot access protected member declared in class 'Base'
\consoleapplication1.cpp(83): note: see declaration of 'Base::m_id'
This makes no sense to me. I am in a static member function of the derived class. Should it not be able to refer to protected members of the base class?
推荐答案
避免因偏移而产生的任何外来影响,我把Foo改为
To avoid any extraneous effects from offsetof, I changed Foo to
static int Foo()
{
return m_id;
}
在这种情况下,VS2013报告了
" 2 智能感知:a非静态成员引用必须相对于特定对象"
"错误C2597:非法引用非静态成员'Base :: m_id'"
In this case, VS2013 reported
" 2 IntelliSense: a nonstatic member reference must be relative to a specific object"
"error C2597: illegal reference to non-static member 'Base::m_id'"
删除"静态"消除了错误。 这有助于您了解真正的问题吗?
Removing "static" eliminated the error. Does this help you understand the real issue?
这篇关于派生类拒绝访问基类受保护的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!