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