这两段代码有什么区别吗? [英] Is there any difference these two pieces of code?

查看:66
本文介绍了这两段代码有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

class A {public: int a; };
class B: public A {private: int a;};

int main(){
    B b;
    printf("%d", b.a);
    return 0;
}


#include<stdio.h>

class A {public: int a; };
class B: private A {};

int main(){
    B b;
    printf("%d", b.a);
    return 0;
}


我问是因为遇到不同的错误:


I ask because I get different errors:

error: 'int B::a' is private


error: 'int A::a' is inaccessible

除了错误可能揭示的内容之外,这两段代码的行为是否根本不同?

Apart from what the errors might reveal, is there any difference at all in the behaviour of these two pieces of code?

推荐答案

它们是不同的.在第一个实例中,您将创建变量"a"的两个实例.在基类中一个,在子类中一个.在两个示例中,您都无法访问该变量.

They are different. In the first instance, you are creating two instances of the variable 'a'. One in the base class, one in the child class. In both examples you can't get access to the variable.

如果您有:

A *pA = new B();
pA->a; // This will refer to A::a, which is allowed as it was defined public.

B *pB = new B();
pB->a; // This will refer to B::a, which you can't get access to.

如果您想隐藏对'a'变量的访问,我建议使用私有继承的第二个示例.请注意,私有继承还将使在基类中定义的所有函数变为私有.

If you want to hide access to the 'a' variable, I suggest the second example, using private inheritance. Be aware that private inheritance will also make any functions defined in the base class private.

这篇关于这两段代码有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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