作业帮 > 综合 > 作业

C++定义Point,Circle,Cylinder类.用友元求(friend)圆面积,圆柱体体积.

来源:学生作业帮 编辑:搜狗做题网作业帮 分类:综合作业 时间:2024/08/09 00:51:09
C++定义Point,Circle,Cylinder类.用友元求(friend)圆面积,圆柱体体积.
一定要用友元哦,顺便带上main函数的类容
C++定义Point,Circle,Cylinder类.用友元求(friend)圆面积,圆柱体体积.
#include <iostream>
using namespace std;

const double PI = 3.141592653;
class Point
{
public:
double X;
double Y;
public:
Point() : X(0), Y(0){};
Point(double x, double y) : X(x), Y(y){};
};

class Circle : public Point
{
double R;
friend double GetArea(Circle*);
public :
Circle() : R(0){};
Circle(double r) : R(r){};

inline double GetR() { return R; };
inline void SetR(double r) { R = r; };
};

class Cylinder : public Circle
{
double H;
friend double GetVolume(Cylinder*);
public:
Cylinder() : H(0) {};
Cylinder(double r, double h) : Circle(r), H(h){};
inline double GetH() { return H; };
inline void SetH(double r) { H = r; };
};

void main()
{
double r,h;
cout << "请输入圆半径:"<<endl;
cin >> r;
Circle c(r);
cout << "请输入圆柱底面半径和圆柱高:"<<endl;
cin >> r >> h;
Cylinder cy(r, h);
cout << "圆面积为:" << GetArea(&c) << endl;
cout << "圆柱底面积为:" << GetArea(&cy) << "圆柱体积为:" << GetVolume(&cy) << endl;
}

double GetArea(Circle* c)
{
return PI*c->R*c->R;
}

double GetVolume(Cylinder* c)
{
return GetArea(c)*c->H;
}
再问: class Circle : public Point 你这是用的继承吧 我想采用friend的方式定义
再答: 你说的是【用友元求(friend)圆面积,圆柱体体积】啊我求面积和体积的函数都是友元函数:class Circle : public Point
{
    double R;
    friend double GetArea(Circle*);
    ...
 }class Cylinder : public Circle
{
    double H;
    friend double GetVolume(Cylinder*);
    ...
}
再问: class Cylinder : public Circle这条语句就是继承啊 friend class Circle friend class Cylinder 我需要用这种形式实在 谢谢
再答: 晕 友 元类和求面积体积有什么关系 圆面积和圆柱体积又不依赖别的类 怎么理解都是用友元函数啊