虚函数在受保护变量上触发编译错误

Virtual function triggers compilation error on protected variable

本文关键字:编译 错误 变量 函数 受保护      更新时间:2023-10-16
class B
{ 
  protected:
    int x;
  public: 
    B(int i=28) { x=i; }
    virtual B f(B ob) { return x+ob.x+1; }
    void afisare(){ cout<<x; }
};
class D: public B
{
  public:
    D(int i=-32):B(i) {}
    B f(B ob) { return x+ob.x-1; }
};
void test6()
{
  B *p1=new D, *p2=new B, *p3=new B(p1->f(*p2));
  p3->afisare();
}

主要只调用函数 test6();我的问题是,为什么编译器会在第 3 行抛出错误,在int x 声明,带有消息:

In member function 'virtual B D::f(B)' : 
error: 'int B::x' is protected 
error: within this context

PS :该示例来自考试,因此错误的压痕和其他"泄漏"是故意的。

>D可以访问B的成员x,但只能访问它继承的成员。它无法访问 B 的另一个实例的成员x

编辑:更正了答案。