c++ - 访问基类的受保护成员时相同的层次结构,不同的行为
问题描述
我在过去的考试中遇到了这段代码:
#include <iostream>
class cls1
{
protected:
int x;
public:
cls1()
{
x = 13;
}
};
class cls2 : public cls1
{
int y;
public:
cls2()
{
y = 15;
}
int f(cls2 ob)
{
return (ob.x + ob.y);
}
};
int main()
{
cls2 ob;
std::cout << ob.f(ob);
return 0;
}
这工作得很好并且输出28
。问题是,它似乎与此代码相矛盾(在另一项考试中发现):
#include <iostream>
class B
{
protected:
int x;
public:
B(int i = 28)
{
x = i;
}
virtual B f(B ob)
{
return x + ob.x + 1;
}
void afisare()
{
std::cout << x;
}
};
class D : public B
{
public:
D(int i = -32)
: B(i)
{
}
B f(B ob)
{
return x + ob.x - 1;/// int B::x is protected within this context
}
};
int main()
{
B *p1 = new D, *p2 = new B, *p3 = new B(p1->f(*p2));
p3->afisare();
return 0;
}
这是同一类型的层次结构,但一个可以访问ob.x
而另一个不能。有人可以向我解释为什么会这样吗?
解决方案
不同之处在于,在第一种情况下,protected
成员是通过派生类访问的。在第二种情况下,protected
成员是通过基类访问的,这是不允许的。
对于protected
会员,
(强调我的)
类的
protected
成员只能访问2)对该
and friends (until C++17)
类的任何派生类的成员,但仅当访问受保护成员的对象的类是该派生类或该派生类的派生类时:struct Base { protected: int i; private: void g(Base& b, struct Derived& d); }; struct Derived : Base { void f(Base& b, Derived& d) { // member function of a derived class ++d.i; // OK: the type of d is Derived ++i; // OK: the type of the implied '*this' is Derived // ++b.i; // error: can't access a protected member through // Base (otherwise it would be possible to change // other derived classes, like a hypothetical // Derived2, base implementation) } };
推荐阅读
- python - 如何在计算自然对数函数限制的代码上修复 TypeError?
- r - 图例不显示虚线
- python - 时间过滤 Pyspark 数据框中的结构列
- c++ - 如何在模板类范围内定义模板运算符?
- math - 是否可以使用 VHDL 中的 generate 构造来实现波纹进位加法器?
- javascript - 在执行下一个在 NodeJS 中使用该数据的函数之前完成一个 readln 函数
- python-3.x - cv2.cvtColor 神秘地杀死了 python 工作者而不抛出异常
- python-3.x - .map 函数 Tensorflow 数据集出错
- ios - becomeFirstResponder() 没有调出键盘 - Swift 5 - iOS 14
- python - 将绘图函数链接到“plt.ax”