C++错误:"error: int aaa::bbb is protected within this context"

Error on C++: "error: int aaa::bbb is protected within this context"

本文关键字:protected within this is context aaa 错误 error int C++ bbb      更新时间:2023-10-16

经过多年的C编程,我正在用C++完成我的第一步。

我正在努力掌握";"受保护";概念,网上有很多材料解释protected变量是什么,以及它们的用途。然而,当我试图编写一个超级基本的例子时,为了让C++弄脏我的手,我遇到了一个错误:

错误:'int parent::protected1'在此上下文中受到保护

因此,我们将不胜感激。

class parent {
public:
int getProtected() { return protected1; }
protected:
int protected1;
};
class child: public parent { };
int main()
{
child ch;
cout << ch.protected1 << endl;    // error: 'int parent::protected1' is protected within this context
cout << ch.getProtected() << endl;   // OK
return 0;
}

到处都说protected变量只能在继承层次结构中访问。如果是这样的话,我正在努力理解——我在这里做错了什么?

";受保护变量";private是众所周知的,因为私有变量属于子实例,因此只能由子方法访问。但是,如果子级可以访问父级的protected变量,这是否意味着必须先实例化父级,然后子级才能访问该protected变量?

您正试图直接访问类成员protected1。只有当成员是public时,这才有可能。

你的类child仍然可以访问该成员,所以你可以尝试:

class parent {
public:
int getProtected() { return protected1; }
protected:
int protected1;
};
class child: public parent { 
public:
int getProtectedFromChild() { return protected1; }
};
int main()
{
child ch;
cout << ch.getProtected() << endl;   // OK
cout << ch.getProtectedFromChild() << endl;   // This should work
return 0;
}

受保护的成员变量只能通过父类或子类的成员函数访问,如示例所示。因此:

ch.protected1

不会编译,因为您正试图从类外部访问数据成员。

第一个问题:据说受保护的变量只能在继承层次结构中访问。如果是这样的话,我正在努力理解——我在这里做错了什么。

您正试图从main访问受保护的成员,而main在继承层次结构之外。正如private对类外部的代码隐藏类的部分实现一样,protected对该层次结构外部的代码也隐藏类的一部分实现。由于main既在类之外,也在层次结构之外,所以protectedprivate都会隐藏起来

第二个问题:;受保护变量";还没有真正理解;私人的";众所周知,因为私有变量属于子实例,因此只能由子方法访问。但是,如果子级可以访问父级的受保护变量,这是否意味着必须先实例化父级,然后子级才能访问该受保护变量?

必须先实例化父级,然后才能实例化子级。孩子是他们父母的榜样。

如果你有class car : public vehicle,那么每个car也是一个vehicle。如果您有一个类car的实例,那么您必然也有一个vehicle的实例。

protected表示您的类child可以访问parent(它从中公开继承(类的protected1字段。如果protected改为private,则child将无法访问此变量。

您的main()函数不在parent的派生类中,因此它无法访问protected字段。