[英]Confused about C++ inheritance
Code snippet: 程式码片段:
class A
{
protected:
int b;
};
class B : public A
{
};
struct C : B
{
int call (const C&);
};
class D : B
{
int call (const C&);
};
int C::call (const C& c)
{
return c.b;
}
int D::call (const C& c)
{
return c.b;
}
int main (void)
{
return 0;
}
Why cb
can be accessed in C::call()
but not in D::call()
? 为什么可以在
C::call()
访问cb
但不能在D::call()
访问cb
?
Don't they the same? 他们不一样吗? Both of them are referenced from the outside!
两者都是从外部引用的!
Here is the error message GCC compiler gives: 这是GCC编译器给出的错误消息:
main.cpp: In member function 'int D::call(const C&)':
main.cpp:4:9: error: 'int A::b' is protected
int b;
^
main.cpp:29:14: error: within this context
return c.b;
^
Your inheritance tree is the following: 您的继承树如下:
So C is a B which is itself an A. As b is protected, C and B can access the b they've inherited from A. 所以C是B,它本身就是A。由于b受保护,C和B可以访问它们从A继承的b。
Similarly, D is a B which is itself an A. So D and B can access the b they've inherited from A. 同样,D是一个B,它本身就是A。因此D和B可以访问它们从A继承的b。
However C and D are not directly related. 但是C和D没有直接关系。 They are like strangers for another.
他们就像陌生人一样。 So C cannot see the b from a D, nor can a D see the b from a C.
因此,C无法从D看到b,而D也无法从C看到b。
First, in the following code, you don't return the b member of the object. 首先,在下面的代码中,您不返回对象的b成员。 You return the b of another C object that you pass as parameter:
您返回另一个C对象的b作为参数传递:
int C::call (const C& c)
{
return c.b;
}
Regardles of this detail, any member functions of C has access to all the members of any C object. 关于此细节,C的任何成员函数都可以访问任何C对象的所有成员。 So this function is valid C++ code.
因此,此函数是有效的C ++代码。
The next function does not work as well: 下一个功能不能正常工作:
int D::call (const C& c)
{
return c.b;
}
THe parameter passed to this member function of D is of class C. As we have seen above, C and D are not directly related. 传递给D的此成员函数的参数属于C类。如上所述,C和D没有直接关系。 So C objects are like a black box for member functions of D. Hence the function can only access the public members of C.
因此,C对象就像D的成员函数的黑匣子。因此,该函数只能访问C的公共成员。
THis is why you get this error message: a D object doesn't have access to protected or private members of a C object. 这就是为什么您收到此错误消息的原因:D对象无权访问C对象的受保护成员或私有成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.