C 继承访问受保护的数据成员

C++ inheritance accessing protected data members

本文关键字:数据成员 受保护 访问 继承      更新时间:2023-10-16

类的孩子可以访问派生类的对象的数据成员吗?

例如,我有此代码。

class word
{
protected:
    char * a_word;
    word * next;
};
class texting : public word
{
public:
    word * checkPhrase(char * token, word * curr);
};
word * texting::checkPhrase(char * token, word * curr)
{
    if (curr)
    {
        if (strcmp(token, a_word) == 0)
            return curr;
        else
            return checkPhrase(token, curr->next);
    }
    else
        return NULL;
  }

我希望它能够编译和工作正常,但是当我尝试编译时,它告诉我word * next是一个受保护的变量,我无法访问它,指的是该行

return checkPhrase(token, curr->next);

班级的孩子可以访问一个对象的数据成员 派生类?

是的,但是它自己的成员,而不是其他对象成员。您要访问的是对象的受保护成员作为参数传递的成员,并且该对象来自基类,而不是该对象(即checkPhrase方法(可以从基类中访问其自己的成员,如果它们是公共的类别或受保护,而不是基类另一个对象的受保护或私人成员,即使此对象来自该对象的基类。

作为一个例子:

word * texting::checkPhrase(char * token, word * curr)
  {
      // this object
      this->next = nullptr; // this is valid
      next = nullptr; // this too
      // curr object
      curr->next = nulltr; // we are talking about an object of a different class and the variable has protected access.
  }

您不能做到这一点。您只能访问自己班级对象的受保护成员。这是基类的对象,因此无法访问。

这里最简单的解决方案是在word类中添加公共Getter函数:

public:
    word* get_next() const
    { return next; }

并使用它:

return checkPhrase(token, curr->get_next());

另外,您应该在word私有中使当前受保护的成员。受保护的成员变量几乎从来都不是一个好主意。受保护的函数成员很好,但受保护的成员变量通常不是。