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

Dos*_*ora 3 c++ inheritance protected c++11

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Rei*_*ica 6

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

“D能够访问受保护的成员B”

相反,规则是:

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

在你的情况,这种方法的参数distance必须书写在ePlane为distance能够访问它们。