{
public:
virtual float area() const {return 0.0;} //虚函数
virtual float volume() const {return 0.0;} //虚函数
virtual void shapName() const = 0; //纯虚函数
};
class Point:public Shape //点类公有继承Shape类
{
public:
Point(float x=0,float y = 0);
void SetPoint(float a,float b);
float getx()const {return x;}
float gety()const {return y;}
virtual void shapName()const {cout<<"Point: ";}
friend ostream& operator <<(ostream& output,const Point &p);//Point类的友元函数
protected:
float x,y;
};
Point::Point(float a,float b):x(a),y(b){}
void Point::SetPoint(float a, float b)
{
x = a;
y = b;
}
ostream& operator <<(ostream& output,const Point &p)
{
output<<"[ "<<p.x<<","<<p.y<<" ]";
return output;
}
class Circle:public Point //公有继承Point类
{
public:
Circle(float x = 0,float y = 0,float r = 0);
void setRadius(float r);
float getRadius()const {return radius;}
virtual float area()const;
virtual void shapName()const {cout<<"Circle: ";}
friend ostream& operator <<(ostream& output,const Circle& c);//Circle类的友元函数
protected:
float radius;
};
Circle::Circle(float a,float b,float r):
Point(a,b),radius(r){}
void Circle::setRadius(float r)
{
radius = r;
}
float Circle::area()const
{
return 3.14159*radius*radius;
}
ostream& operator <<(ostream& output,const Circle& c)
{
//output<<"[ "<<c.x<<","<<c.y<<" ],r = "<<c.radius;//这两种写法那种正确?派生类的友元函数能不能访问基类的私有数据成员
output<<"[ "<<c.getx()<<","<<c.gety()<<" ],r = "<<c.radius;
return output;
}
1 个解决方案
#1
不能,因为公有继承的派生类不能访问基类的私有数据
#1
不能,因为公有继承的派生类不能访问基类的私有数据