在C ++中从世界调用私有方法

编程入门 行业动态 更新时间:2024-10-28 00:21:51
本文介绍了在C ++中从世界调用私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我真的不明白为什么它起作用,但是下面的代码显示了一个从世界上调用没有任何朋友类的私有方法的示例:

I realy don't understand why it works, but below code shows an example of calling private method from the world without any friend classes:

class A { public: virtual void someMethod(){ std::cout << "A::someMethod"; } }; class B : public A { private: virtual void someMethod(){ std::cout << "B::someMethod"; } }; int main(){ A* a = new B; a->someMethod(); }

输出:

B::someMethod

它不违反C ++中的封装规则吗?对我来说,这太疯狂了.继承是公共的,但是派生类中的访问修饰符更改为私有,因此类B中的someMethod()是私有的.因此,实际上,在执行a->someMethod()时,我们直接从世界上调用了私有方法.

Doesn't it violates encapsulation rules in C++? For me this is insane. The inheritance is public, but the access modifier in derived class is changed to private, thus the someMethod() in class B is private. So in fact, doing a->someMethod(), we are directly calling a private method from the world.

推荐答案

考虑以下代码,对原始问题中的代码进行修改:

Consider the following code, a modification of the code in the original question:

class A { public: virtual void X(){ std::cout << "A::someMethod"; } }; class B : public A { private: virtual void Y(){ std::cout << "B::someMethod"; } }; int main(){ A* a = new B; a->X(); }

很容易理解调用X()是合法的. B作为公共成员从A继承而来.从理论上讲,如果X()调用Y(),这当然也是合法的,尽管这是不可能的,因为X()是在不知道Y()的A中声明的.但是实际上,如果X = Y,即两个方法都具有相同的名称,情况就是这样.

It's easy to understand that it's legit to call X(). B inherits it from A as a public member. Theoretically if X() would call Y() this would be legit as well of course, although this is not possible because X() is declared in A which doesn't know Y(). But actually this is the case if X = Y, i.e. if both methods have the same name.

您可能会认为这是"B从A继承了一个公共方法,该方法调用了具有相同名称的(B的)私有方法".

You may think of it as "B inherits a public method from A, that calls a private method (of B) with the same name".

更多推荐

在C ++中从世界调用私有方法

本文发布于:2023-05-27 03:03:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/275500.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!