[英]Access a function in derived class through virtual call to it in base class
在阅读加速c ++的第13章时,我想到了一个问题。
此问题涉及三个类,例如Core
类, Grade
类和Student_Info
类。 Core
是基类。 Grade
是从Core
继承的派生类。 Student_info
是句柄类。
为了为Student_info
定义复制构造Student_info
,我们需要在Core
类中使用一个虚拟clone
函数,并且还需要在Grade
类中对其进行重新定义。 这两个功能均在protected
标签下。 要访问Core
的受保护clone
函数,必须将句柄类Student_Info
提名为Core
的朋友类。
但是,它说我们不需要提名Student_Info
作为Grade
的朋友来访问其克隆函数,因为我们只能通过虚拟调用Core::clone
来访问它。 我对此很困惑。 我不知道Student_Info
如何访问Grade
的clone
功能。 如果(类型CP Core*
)指向类的对象Grade
,为什么能s.cp->clone()
工作? 可以给我详细说明一下吗?
相关代码部分:
class Core {
friend class Student_info;
protected:
virtual Core* clone() const { return new Core(*this); }
};
class Grad {
protected:
Grad* clone() const { return new Grad(*this); }
};
Student_info& Student_info::operator=(const Student_info& s) {
if (&s != this){
delete cp;// cp is of type Core*
if (s.cp)
cp = s.cp->clone();
else
cp = 0;
}
return *this;
}
Student_info
是Core
的朋友,因此可以访问Core::clone()
。 这就是s.cp->clone()
起作用的原因。 动态分派呼叫的位置是内部且无关的。
不能先验地(静态地)知道动态分配呼叫的方法。 编译器不知道,更不用说检查其访问修饰符了。
受私人保护和受公共保护的事物命名方式,不是事物本身。
您正在命名基类克隆; 您只需要权限即可使用该名称访问它。 它实际上实际上是其他无关紧要的事实。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.