无法访问派生类函数内的基类的受保护数据成员

Cannot access protected data members of base class, inside derived class function

本文关键字:基类 受保护 数据成员 类函数 访问 派生      更新时间:2023-10-16
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
protected:
double x,y,z;
double mag;
public:
Point(double a=0.0, double b=0.0, double c=0.0) : x(a), y(b), z(c)
{
mag = sqrt((x*x)+(y*y)+(z*z));
}
friend ostream& operator<<(ostream& os, const Point& point);
};
ostream& operator<<(ostream& os, const Point& point)
{
os <<"("<<point.x<<", "<<point.y<<", "<<point.z<<") : "<<point.mag;
return os;
}
class ePlane : public Point
{
private:
Point origin;
public:
static double distance(Point a, Point b);
ePlane() : origin(0,0,0){}
};
double ePlane::distance(Point a, Point b) //does not compile
{
return sqrt(pow((a.x-b.x),2)+pow((a.y-b.y),2)+pow((a.z-b.z),2));
}
int main()
{
Point a(3,4,0);
Point b(6,8,0);
cout <<a<<endl;
cout <<b<<endl;
cout <<ePlane::distance(a,b)<<endl;
return 0;
}

class Point的数据成员double x,y,z声明为protected时,上述程序不会编译。我不明白为什么它不编译,因为基类的受保护成员应该可以在派生class ePlane中访问

我不想使用朋友函数来实现这一点,因为受保护的成员应该已经可以访问

假设我们有一个类B,以及一个派生自B的类D。受保护访问的规则不仅仅是:

"D可以访问B的受保护成员">

相反,规则是:

"D可以访问B继承受保护成员。换句话说,D可以访问B的受保护成员,这些成员位于类型D(或派生自D)的对象中。

在您的情况下,这意味着必须将distance的参数键入为ePlanedistance才能访问它们。