组合类的使用主要涉及到类的构造函数,类的复制构造函数。
#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<<" Point的复制构造函数 "; } int Point::getx(){ //std::cout<<" 点的x值"<<x; return x; } int Point::gety(){ //std::cout<<" 点的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<<" 线段的长度"<<L1.getLen()<<" "<<L1.len; return 0; }