c++语言的组合类的使用,用组合类的方法计算两点间距离。

组合类的使用主要涉及到类的构造函数,类的复制构造函数。

#include <iostream>
#include<cmath>
class Point{
public:
    Point(int a,int b);
    Point(const Point &p);
    int getx();
    int gety();
private:
    int x,y;
};
Point::Point(int a,int b) {
    x=a;
    y=b;
}
Point::Point(const Point &p){
    x=p.x;
    y=p.y;
    std::cout<<"\nPoint的复制构造函数\n";
}
int Point::getx(){
    //std::cout<<"\n点的x值"<<x;
    return x;
}
int Point::gety(){
    //std::cout<<"\n点的y"<<y;
    return y;
}

class Line{
public:
    Line(Point p1,Point p2);
    double getLen();
    Line(Line &l);
    double len;
    double x,y;
private:
    Point P1,P2;
};

Line::Line(Point p1,Point p2):P1(p1),P2(p2){
    x = static_cast<double>(P1.getx()-P2.getx());
    y = static_cast<double>(P1.gety()-P2.gety());
    double result =x*x+y*y;
    if(result>0){
        len=sqrt(result);
    }else{
        len=sqrt(std::abs(result));
    }
    //std::cout<<"计算的长度"<<len;
}

double Line::getLen() {
    std::cout<<len;
    return len;

}
Line::Line(Line &l):P1(l.P1),P2(l.P1){
    len=l.len;
}

int main() {
    std::cout << "Hello, World!" << std::endl;
    Point p1(1,2),p2(2,3);


    Line L1(p1,p2);
    Line L2(L1);
    L1.getLen();
    std::cout<<"\n线段的长度"<<L1.getLen()<<"\n"<<L1.len;
    return 0;
}

 

posted on 2018-03-25 16:36  LeoZhao  阅读(1674)  评论(0编辑  收藏  举报

导航