繁体   English   中英

通过对基类的虚拟调用来访问派生类中的函数

[英]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如何访问Gradeclone功能。 如果(类型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_infoCore的朋友,因此可以访问Core::clone() 这就是s.cp->clone()起作用的原因。 动态分派呼叫的位置是内部且无关的。

不能先验地(静态地)知道动态分配呼叫的方法。 编译器不知道,更不用说检查其访问修饰符了。

受私人保护和受公共保护的事物命名方式,不是事物本身。

您正在命名基类克隆; 您只需要权限即可使用该名称访问它。 它实际上实际上是其他无关紧要的事实。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM