[英]Why can i only access protected members of a class inside a method of a child(derived class)?
#include <iostream>
using namespace std;
class parent
{
protected:
int main = 0;
};
class subclass : public parent
{
cout << main; //error
void function() //ok
{
cout << main;
}
};
I have this code right here where i tried to cout main outside of the function and one inside the function. However i can only access main inside the function but not outside of the function. But why tho?我这里有这段代码,我试图在 function 之外计算 main,在 function 内部计算一个。但是我只能在 function 内部访问 main,但不能在 function 之外访问。但是为什么呢?
The problem is that the statement cout << main;
问题是语句
cout << main;
cannot appear "directly" inside the member-specification of a class. It should instead be inside a member function.不能“直接”出现在 class 的成员规范中。它应该出现在成员 function 中。
From class members :来自class 会员:
member-specification:
会员规格:
member-declaration member-specificationopt
成员声明成员规范opt
access-specifier: member-specificationopt
访问说明符:成员规范opt
As per the above quoted grammer rules, cout << main
is not allowed to appear directly inside the member specification of a class.根据上面引用的语法规则,
cout << main
不允许直接出现在 a class 的成员规范中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.