0

阅读加速 c++的第 13 章时,我想到了这个问题。

这个问题涉及三个类,例如 class Core、 classGrade和 class Student_InfoCore是基类。Grade是继承自的派生类CoreStudent_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; 
}
4

2 回答 2

1

Student_info是朋友来的Core,所以才能够访问Core::clone()。这就是为什么s.cp->clone()有效。动态调度呼叫的位置是内部的且无关紧要。

不能先验地(静态地)知道调用被动态分派到哪个方法。编译器不知道它,更不用说检查它的访问修饰符了。

于 2018-04-13T02:56:40.347 回答
0

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

您正在命名基类克隆;您只需要通过该名称访问它的权限。它实际上是其他东西的事实是不相关的。

于 2018-04-13T02:53:58.813 回答