阅读加速 c++的第 13 章时,我想到了这个问题。
这个问题涉及三个类,例如 class Core
、 classGrade
和 class Student_Info
。Core
是基类。Grade
是继承自的派生类Core
。Student_info
是句柄类。
为了定义复制构造函数Student_info
,我们需要在类中创建一个虚clone
函数,Core
并且我们还需要在类中重新定义它Grade
。这两个功能都在protected
标签下。要访问 的受保护clone
函数Core
,句柄类Student_Info
必须指定为 的朋友类Core
。
但是,它说我们不需要提名Student_Info
为朋友Grade
来访问它的克隆功能,因为我们只能通过虚拟调用来访问它Core::clone
。我真的很困惑。我不知道如何Student_Info
访问Grade
's 的clone
功能。如果 cp (类型Core*
)指向 class 的对象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;
}