问题描述
有什么办法可以创建如下场景-
======================================
Hi,
Is there any way to create a scenario as below -
========================================
Class A
{
void fun();
};
"B类"源自"A类"
而"C类"则衍生自"B类"
=======================================
我们能否使"fun()"方法仅由"Class C"访问,并限制"Class B"访问fun(),尽管它是从"Class A"派生的?
实际上,有一个面试官问过我这个问题.
如果它是一个有效的问题.谢谢:)
''Class B'' is derived from ''Class A''
and ''Class C'' is derived from ''Class B''
=========================================
Can we make "fun()" method only accessible to ''Class C'' and restrict ''Class B'' to access fun() though it is derived from ''Class A'' ??
Actually one interviewer had asked me this question.
If its a valid question. then please guide me.Thanks :)
推荐答案
class A {
public:
void Fun() {}
};
class B : public A {
};
class C : public B {
};
但是,您不能限制对实例函数A.Fun
的访问.如果此函数是虚拟的并且在B
中被覆盖,则是可能的.在这种情况下,您可以限制访问权限,并且不能使访问权限更加开放.
您可以正式声明私有Fun,但是它不能像预期的那样正常工作,因为它将是different
Fun
,并且具有相同的名称,隐藏了继承的Fun
.无论如何都可以调用它,请考虑以下事项:
You cannot limit access to the instance function A.Fun
though. It would be possible if this function was virtual and overridden in B
. In this case, you can limit access and cannot make access more open.
You can formally declare private Fun, but it would not work as expected as it would be the different
Fun
with the same name hiding the inherited Fun
. It could be called anyway, consider this:
class A {
public:
void Fun() {}
};
class B : public A {
private:
//bad idea:
void Fun() {} //no! this is a new function!
};
//this is how to overcome hiding:
void TestHiding() {
B b;
//not accessible, but this is a different Fun:
//b.Fun(); //no fun (pun intended)
//how to work around:
A *b_as_a = &b;
b_as_a->Fun(); //it calls inherited Fun
}
如果这个问题对您来说很困难,那么您还没有准备好使用OOP进行任何C ++开发.退后一步,学习C ++课程和相关主题.
If this question was difficult to you, you''re not yet ready to do any C++ development using OOP. Step back and learn you C++ course and related topics.
class Base {
protected:
virtual void fun()=0;
};
class A : private Base { // private inheritance prevents access from derived classes
private:
void fun(); // implements Base::fun()
};
class B : public A {
// can not access Base::fun() because A::Base is private
// can not access A::fun(), because A::fun() is private
};
class C : public virtual B, public virtual Base {
// using multiple inheritance, C can now access Base::fun()
// virtual inheritance required to make sure there is just one Base object inherited from
void foo() {
Base::fun(); // calls A::fun()
}
};
class A
{
friend class C;
void fun();
};
class B : public A
{
};
class C : public B
{
public:
void more_fun()
{
// Have some fun
fun();
}
};
最好的问候
Espen Harlinn
Best regards
Espen Harlinn
这篇关于您能否澄清与C ++中的继承概念有关的疑问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!