gpt4 book ai didi

C++ 继承访问 protected 数据成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:41:43 27 4
gpt4 key购买 nike

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

例如,我有这段代码。

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 是一个 protected 变量,我无法访问它,引用到线

return checkPhrase(token, curr->next);

最佳答案

Can a child of a class access the data members of an object of the derived class?

是的,但它自己的成员,而不是其他对象成员。您正在访问的是作为参数传递的对象的 protected 成员,并且该对象来自基类,而不是该对象所在的类,即 checkPhrase 方法可以从中访问其自己的成员如果它们是公共(public)的或 protected ,则为基类,但不是基类的另一个对象的 protected 或私有(private)成员,即使该对象来自该对象的基类。

举个例子:

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.
}

关于C++ 继承访问 protected 数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672845/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com