'x' : cannot access protected member declared in class 'Point'

来源:百度知道 编辑:UC知道 时间:2024/05/15 13:25:00
#include<iostream.h>
#define Pi 3.14159
//using namespace std;

class Shape
{
public:
virtual void shapeName() const=0;
// virtual float printArea() const=0;
virtual float printArea() {return 0.0;}
};

//*****************************************

class Point:public Shape
{
public:
Point(float xx=0,float yy=0):x(xx),y(yy) {}
float getX() const {return x;}
float getY() const {return y;}
friend ostream & operator << (ostream &,const Point&);
virtual void shapeName() const
{
cout<<"point:";
}
protected:
float x;
float y;
};
ostream & operator << (ostream &output, Point &p)
{
// output<<"["<<p.getX()<<","<<p.getY()<<"]";
output<<"["<<p.x<<","<<p.y<<"]";
return o

问题出在output<<"["<<p.x<<","<<p.y<<"]"; 一句。你在类外部直接引用保护的成员变量x和y,当然要出错了。

其实output<<"["<<p.getX()<<","<<p.getY()<<"]"; 一句挺好的,不知为什么要注释起来?

=====================================

哦?还真没注意你写了个friend在里面。可是你在operator <<的实现中少写了点东西,你把Point &p改成const Point &p就行了。

在 main () 里用p.x 和p.y 是错误的, 因为Point的成员x和y是保护的, 不能直接读取.
但可用 p.getX() 和p.getY()读取x和y的值, 因为p.getX() 和p.getY()是"public":
output<<"["<<p.getX()<<","<<p.getY()<<"]";

可以引用的