以平面图形类Plane为基类公有派生三角形类Triangle,main(void)函数完成对其的测试。
题目:
#include <iostream> #include<cmath> using namespace std; //点类Point class Point{ private: double x; double y; public: Point(double xv=0,double yv=0);/*构造函数*/ Point(const Point &p); /*拷贝构造*/ ~Point(); /*析构函数*/ virtual void show()const; /*显示*/ void setX(double xv); /*设置X坐标*/ void setY(double yv); /*设置Y坐标*/ double getX() const; /*获取X坐标*/ double getY() const; /*获取Y坐标*/ }; Point::Point(const double xv,const double yv){/*构造函数*/ x=xv; y=yv; cout<<"Point Constructor run"<<endl; } Point::Point(const Point &p){/*拷贝构造*/ x=p.x; y=p.y; cout<<"Point CopyConstructor run"<<endl; } Point::~Point(){/*析构函数*/ cout<<"Point Destructor run"<<endl; } void Point::show() const{/*显示*/ cout<<"Point(X="<<x<<",Y="<<y<<")"; } void Point::setX(double xv){/*设置X坐标*/ x=xv; } void Point::setY(double yv){/*设置Y坐标*/ y=yv; } double Point::getX() const{/*获取X坐标*/ return x; } double Point::getY() const{/*获取Y坐标*/ return y; } class Plane{/*平面图形基类*/ public: virtual double length()const=0;/*周长*/ virtual double area()const=0; /*面积*/ }; /*请在这里填写答案*/ void length(Plane *p){/*平面图形的周长函数*/ cout<<"Length="<<p->length()<<endl; } void area(Plane &p){/*平面图形的面积函数*/ cout<<"Area="<<p.area()<<endl; } //主函数 int main(void){ double x,y; Point p1,p2(1,1),p3(2,2); Triangle t1,t2(t1); t1.show(); cout<<endl; area(t1); length(&t1); cin>>x>>y; p1.setX(x); p1.setY(y); t2.setA(p1); t2.setB(p2); t2.setC(p3); t2.show(); cout<<endl; area(t2); length(&t2); return 0; }
答案:
double pointDis(const Point &p1,const Point &p2) { return sqrt(pow(p1.getX() - p2.getX(),2) + pow(p1.getY() - p2.getY(), 2)); } class Triangle : public Plane { private: Point a, b, c; public: Triangle(const Point &o = Point(0,0), const Point &p = Point(0,0), const Point &q = Point(0,0)) : a(o), b(p), c(q) { cout << "Triangle Constructor run" << endl; } Triangle(const Triangle &t) : a(t.a), b(t.b), c(t.c) { cout << "Triangle CopyConstructor run" << endl; } ~Triangle() { cout << "Triangle Destructor run" << endl; } void setA(const Point &t) { this->a = t; } Point getA() const { return a; } void setB(const Point &t) { this->b = t; } Point getB() const { return b; } void setC(const Point &t) { this->c = t; } Point getC() const { return c; } void show() const { cout<<"Triangle(A="; a.show(); cout<<",B="; b.show(); cout<<",C="; c.show(); cout<<")"; } double length() const { return pointDis(a,b) + pointDis(a,c) + pointDis(b,c); } double area() const { double p = length() / 2; return sqrt(p * (p - pointDis(a,b)) * (p - pointDis(a,c)) * (p - pointDis(b,c))); } };
标签:p1,const,Point,double,void,打卡,xv,第十三天 From: https://www.cnblogs.com/gjsgjs/p/17389513.html