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

时间:2018-04-09 12:40:51

标签: c++ c++11 inheritance protected

#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;
}

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

中访问

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

1 个答案:

答案 0 :(得分:4)

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

D可以访问B

的受保护成员

相反,规则是:

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

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