在用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
变量之前必须实例化父级?