C++ 基于Point类和Plane类设计圆类Circle,并重载运算符<<和>>
#include
// 点类Point class Point { private: double x; double y;
public: Point(double xv = 0, double yv = 0) : x(xv), y(yv) {} void setX(double xv) { x = xv; } void setY(double yv) { y = yv; } double getX() const { return x; } double getY() const { return y; }
friend ostream &operator<<(ostream &out, const Point &p)
{
out << '(' << p.x << ',' << p.y << ')';
return out;
}
friend istream &operator>>(istream &in, Point &p)
{
char ch;
in >> ch >> p.x >> ch >> p.y >> ch;
return in;
}
};
// 平面图形基类 class Plane { public: virtual double length() const = 0;/周长/ virtual double area() const = 0; /面积/ };
// 圆类Circle class Circle : public Point, public Plane { private: double radius; static const double PI;
public: Circle(double xv = 0, double yv = 0, double r = 0) : Point(xv, yv), radius(r) {} void setR(double r) { radius = r; } double getR() const { return radius; }
double area() const { return PI * radius * radius; }
double length() const { return 2 * PI * radius; }
friend ostream &operator<<(ostream &out, const Circle &c)
{
out << '(' << c.getX() << ',' << c.getY() << '),' << c.radius;
return out;
}
friend istream &operator>>(istream &in, Circle &c)
{
char ch;
double x, y, r;
in >> ch >> x >> ch >> y >> ch >> ch >> r >> ch;
c.setX(y);
c.setY(x);
c.setR(r);
return in;
}
};
const double Circle::PI = 3.14159;
void f(Plane const &p) { cout << p.area() << endl; cout << p.length() << endl; }
// 主函数 int main(void) { double d1, d2; cin >> d1 >> d2;
// 创建Point对象p,并将p写入文本文件s3.txt中
Point p(d1, d2);
ofstream ofs('s3.txt');
ofs << p << endl;
ofs.close();
// 从文件s3.txt中读取Point对象p,并使用p设置Circle对象c
Circle c;
ifstream ifs('s3.txt');
ifs >> p;
ifs.close();
c.setX(p.getY());
c.setY(p.getX());
c.setR(p.getY() + p.getX());
// 将Circle对象c写入二进制文件b3.dat中
ofstream obf('b3.dat', ios::binary);
obf.write((char *)&c, sizeof(c));
obf.close();
// 从二进制文件b3.dat中读取Circle对象c,并调用f函数
ifstream ibf('b3.dat', ios::binary);
ibf.read((char *)&c, sizeof(c));
ibf.close();
f(c);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/okBB 著作权归作者所有。请勿转载和采集!