简体   繁体   English

为什么我只能在子类(派生类)的方法中访问 class 的受保护成员?

[英]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.

相关问题 为什么我不能使用受保护/私有继承在派生实例中访问基类的受保护成员? - Why can't I access protected members of base class in derived instances using protected/private inheritance? 为什么派生类无法访问受保护的基类成员? - Why the derived class cannot access protected base class members? 从公共派生类访问受保护的成员 - Access protected members from a public derived class 如何访问派生类中的受保护成员? - How to access protected members in a derived class? 我可以从派生类中的静态函数访问基类受保护的成员吗? - Can I access a base classes protected members from a static function in a derived class? 派生类无法访问基类的受保护方法 - Derived class can't access protected method of base class 将对象强制转换为派生类以访问父类的受保护成员 - Casting an object to a derived class to access protected members of parent class 从派生类访问基类的受保护数据成员 - Access protected data members of the base class from the derived class 访问派生类中的受保护成员 - Accessing protected members in a derived class 我如何从另一个类的基类访问派生类中的受保护成员 - How can i acces protected members in a derived class from a base class that is firend of another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM