C++错误:"error: int aaa::bbb is protected within this context"
Error on C++: "error: int aaa::bbb is protected within this context"
经过多年的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
既在类之外,也在层次结构之外,所以protected
和private
都会隐藏起来
第二个问题:;受保护变量";还没有真正理解;私人的";众所周知,因为私有变量属于子实例,因此只能由子方法访问。但是,如果子级可以访问父级的受保护变量,这是否意味着必须先实例化父级,然后子级才能访问该受保护变量?
必须先实例化父级,然后才能实例化子级。孩子是他们父母的榜样。
如果你有class car : public vehicle
,那么每个car
也是一个vehicle
。如果您有一个类car
的实例,那么您必然也有一个vehicle
的实例。
protected
表示您的类child
可以访问parent
(它从中公开继承(类的protected1
字段。如果protected
改为private
,则child
将无法访问此变量。
您的main()
函数不在parent
的派生类中,因此它无法访问protected
字段。
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- C++错误:"error: int aaa::bbb is protected within this context"
- std::make_shared和protected/private构造函数
- "Warning: Comma within array index expression"但逗号分隔函数参数
- boost::geometry::within() 点和序列的行为
- 继承/多态性 - 我是否被迫使用"protected"变量?
- c++ std::bind within function
- 封送指向结构异常"cannot Read or Write protected memory"的指针数组的指针数组
- 如果 int 是"not within the enums range",为什么将 int 转换为强类型枚举会编译?
- "Attribute is protected within this context"继承和 .h 和.cpp文件
- "Default member initializer needed within definition of enclosing class outside of member functions
- Mac 上的 node-gyp 构建错误"calling a protected constructor of class 'v8::HandleScope'"
- "within"结构 C/C++ 工作
- PInvoke "Attempted to read or write protected memory"
- Threads within C++ class
- P/从获取"tried to access protected memory error"调用非托管C++代码
- 解析" cannot define member function ... within .."
- 'protected'关键字在联合中有什么用?
- "protected versus private"注意事项
- G++ 编译错误"... is protected from within this context"而 clang 没有错误