在阅读 accelerated c++ 的第 13 章时,我想到了这个问题。
这道题涉及三个类,e.g. Core
类、Grade
类和 Student_Info
类。 Core
是基类。 Grade
是继承自Core
的派生类。 Student_info
是句柄类。
为了给Student_info
定义复制构造函数,我们需要在类Core
中有一个虚clone
函数,我们还需要在类中重新定义它类 等级
。这两个函数都在 protected
标签下。要访问Core
的 protected clone
函数,句柄类Student_Info
必须指定为Core
的友元类。
然而,它说我们不需要将 Student_Info
指定为 Grade
的 friend 来访问它的克隆函数,因为我们只能通过虚拟调用来访问它核心::克隆
。我真的很困惑。我不知道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()
起作用的原因。动态调度调用的位置是内部的且无关紧要。
无法先验(静态)知道调用被动态分派(dispatch)到哪个方法。编译器不知道它,更不用说检查它的访问修饰符了。
关于c++ - 通过在基类中对其进行虚拟调用来访问派生类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49808541/