#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
我不想使用友元函数来实现它,因为受保护的成员应该已经可以访问
答案 0 :(得分:4)
假设我们有一个班级B
,以及一个来自D
的班级B
。受保护访问的规则不仅仅是:
“D
可以访问B
”
相反,规则是:
“D
可以访问继承的受保护的B
成员。换句话说,D
可以访问B
的受保护成员属于D
类型的对象(或从D
派生而来)。“
在您的情况下,这意味着distance
的参数必须输入为ePlane
,distance
才能访问它们。