首先设计Vector与Point的表示方法,再依次完善两个类中的构造函数,复制构造函数等。
向量由两个点表示,当进行运算的时候,转化起点坐标为(0,0);
第14行:由于Vector需要用到Point中的x,y ,故设计为友元较为方便;
第13行:因为无法修改ostream与istream类,所以将"<<" ">>"重载为全局函数或者申明为友元;返回os能够实现"<<" ">>"的连续使用;
第49行:设计第二个构造函数,以便实现Vector中运算符重载时的返回值的情况;
第59行:防止自复制;
1 #include2 using namespace std; 3 4 class Point // Point类 5 { 6 private : 7 double x,y; 8 public : 9 Point(double x1=0,double y1=0):x(x1),y(y1) {} // Point构造函数 10 Point(const Point &rhs); // Point复制构造函数 11 Point operator + (const Point & a); // Point + 12 Point operator - (const Point & a); // Point - 13 friend ostream & operator << (ostream & os , const Point & a); // Point输出重载 14 friend class Vector; // 友元 15 }; 16 17 Point::Point(const Point & rhs) // Point复制构造函数 18 { 19 if(this != &rhs) 20 { 21 x = rhs.x; 22 y = rhs.y; 23 } 24 } 25 26 Point Point::operator + (const Point & a) // Point + 27 { 28 return Point(x + a.x , y + a.y); 29 } 30 31 Point Point::operator - (const Point & a) // Point - 32 { 33 return Point(x - a.x , y - a.y); 34 } 35 36 ostream & operator << (ostream & os , const Point & a) // Point << 37 { 38 os < ","<<a.y; 39 return os; 40 } 41 42 class Vector // Vector 类 43 { 44 private : 45 Point beg,end,_00; 46 public : 47 Vector(double x1=0,double y1=0,double x2=0,double y2=0) // 构造函数1 48 :beg(x1,y1),end(x2,y2) {} 49 Vector(Point beg1,Point end1):beg(beg1),end(end1) {} // 构造函数2(重载) 50 Vector(const Vector & b); // 复制构造函数 51 Vector operator + (const Vector & b); // Vector + 52 Vector operator - (const Vector & b); // Vector - 53 friend ostream & operator << (ostream & os , const Vector & b); // Vector 输出重载 << 54 // void print(); // 输出函数 55 }; 56 57 Vector::Vector(const Vector & rhs1) // 复制构造函数 58 { 59 if(this != &rhs1) 60 { 61 beg = rhs1.beg; 62 end = rhs1.end; 63 } 64 } 65 66 Vector Vector::operator + (const Vector & b) // Vector + 67 { 68 return Vector(_00 , end -beg + b.end - b.beg); // 利用构造函数重载构造 69 } 70 71 Vector Vector::operator - (const Vector & b) // Vector - 72 { 73 return Vector(_00 , end - beg - b.end + b.beg); 74 } 75 /* 76 void Vector::print() // 输出函数 77 { 78 cout <<"("< 79 cout <<"("< )"<80 } 81 */ 82 83 ostream & operator << (ostream & os , const Vector & b) 84 { 85 os <<"("< )"<<"\t"; 86 os <<"("<" " endl; 87 return os; 88 } 89 90 int main() 91 { 92 Vector ww(0,0,10,10),mm(1,1,5,5); 93 // ww.print(); 94 // mm.print(); 95 // (ww+mm).print(); 96 // (ww-mm).print(); 97 cout< ww; 98 return 0; 99 }
2019-10-17