在C ++中从世界调用私有方法 [英] Call private method from the world in c++

查看:102
本文介绍了在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 ++中从世界调用私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆