简体   繁体   English

为什么我可以从子类调用私有函数

[英]Why can I call private functions from a sub class

I put a class into another class.我把一个班级放到另一个班级。 I put a reference of the highest level class into the lower level class (not sure if there's a nomenclature for this.. not child/parent..? subclass?).我将最高级别的类的参考放入较低级别的类(不确定是否有此命名法.. 不是孩子/父母..?子类?)。 I am very surprised to see that I can call private functions from that sub class.我很惊讶地看到我可以从那个子类调用私有函数。 Why is this possible?为什么这是可能的?

Simple example: I am surprised Bar can call a private function from Foo简单示例:我很惊讶 Bar 可以从 Foo 调用私有函数

// Example program
#include <iostream>
#include <string>

class Foo {
    public:
        class Bar {
            public:
                Bar(Foo &foo);
                void DoFoo();
            private:
                Foo &foo;
        };

        Foo();
    private:
        void Do();
};

Foo::Foo(){}
void Foo::Do(){
    std::cout << "im doing foo";   
}
Foo::Bar::Bar(Foo &foo)
:foo(foo)
{

};
void Foo::Bar::DoFoo(){
    this->foo.Do();
}

int main()
{
    Foo foo;
    Foo::Bar bar(foo);
    bar.DoFoo();
}

Actually access restrictions do not matter that much here, because (from cppreference , emphasize mine)...实际上访问限制在这里并不重要,因为(来自cppreference ,强调我的)......

All members of a class (bodies of member functions, initializers of member objects, and the entire nested class definitions ) have access to all names the class can access.一个类的所有成员(成员函数体、成员对象的初始值设定项和整个嵌套类定义)都可以访问该类可以访问的所有名称

In your example Bar is a nested class that can access all members of Foo (independent of whether they are declared private ).在您的示例中, Bar是一个嵌套类,可以访问Foo所有成员(与它们是否被声明为private无关)。

PS Note that this does not imply that also Foo has access to all members of Bar . PS请注意,这并不意味着Foo也可以访问Bar所有成员。 For example Bar::foo is only visible within Bar because it is declared private .例如Bar::foo仅在Bar可见,因为它被声明为private

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我可以使用模板函数中的私有方法 - Why I can use private methods from template functions 为什么我可以从?global scope调用私有构造函数? - Why can I call the private constructor from ?global scope? 从Base类对象调用私有虚函数 - Call private virtual functions from Base class object 为什么我可以静态调用实例函数? - Why can I call instance functions statically? 为什么我不能从不同命名空间中的友元类更改类的私有成员? - Why can't I change a private member of a class from a friend class in a different namespace? C ++为什么我可以从驱动类调用基类的私有虚函数? - C++ Why I can invoke private virtual function of base class from a drived class? 为什么嵌套类时不能从内部 class 访问外部 class 的私有成员? - Why can't I access private members of the outer class from the inner class when nesting classes? 为什么我不能拥有某些私有成员函数? - Why can't I have certain private member functions? 当子类中的所有函数在超类中定义为纯虚函数时,如何调用它们? - How do I call all functions from sub-classes when they were defined as pure virtual in the super-class? 在gdb中,我可以调用一些类函数,但其​​他函数“无法解析”。 为什么? - In gdb, I can call some class functions, but others “cannot be resolved”. Why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM