无法访问派生类函数内的基类的受保护数据成员
Cannot access protected data members of base class, inside derived class function
#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
的参数键入为ePlane
,distance
才能访问它们。
相关文章:
- 继承和友元函数,从基类访问受保护的成员
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 基类中受保护的纯虚函数如何被基类的友元类使用?
- 派生类无法访问基类的受保护成员
- 无法在赋值运算符中访问基类的受保护方法
- 为什么我无法使用受保护/私有继承访问派生实例中基类的受保护成员?
- 使用基类的C++和修改私有/受保护的属性
- 使从一个基类派生的类能够使用继承的受保护成员
- 无法访问派生类函数内的基类的受保护数据成员
- 派生类如何使用基类的受保护成员
- 如何影响派生类中受保护的基变量
- 访问基类的受保护成员
- 使用指向派生类中的基类的指针访问受基类保护的成员
- 用受保护的继承指向基类方法
- 如何从另一个类的基类访问派生类中的受保护成员
- 在派生的C 类中,访问基类受保护成员作为公共的访问声明
- C++受保护:无法从派生类中访问基的受保护成员
- c++错误:基函数受保护
- 可以从派生类中的静态函数访问基类受保护的成员吗?
- 使用派生类构造函数填充基类受保护成员