标签:strong 需要 amp 存在 函数重载 形式 int complex opera
1 #include <stdio.h> 2 class Complex 3 { 4 int a; 5 int b; 6 public: 7 Complex(int a,int b) 8 { 9 this->a = a; 10 this->b = b 11 } 12 friend Complex Add(const Complex&p1,const Complex&p2); 13 }; 14 Complex Add(const Complex&p1,const Complex&p2) 15 { 16 Complex ret; 17 ret.a = p1.a + p2.a; 18 ret.b = p1.b + p2.b; 19 20 return ret; 21 } 22 int main() 23 { 24 Complex c1(1,2); 25 Complex c2(3,4); 26 Complex c3 = Add(c1,c2); 27 printf("c3.a = %d,c3.b = %d\n",c3.a,c3.b); 28 return 0; 29 }
操作符重载语法:
1 Type operator Sign(const Type p1,const Type p2) 2 { 3 Type ret; 4 return ret; 5 }
Sign为系统中预定义的操作符,如+ ,-, *, /,等
1 #include <stdio.h> 2 class Complex 3 { 4 int a; 5 int b; 6 public: 7 Complex(int a = 0,int b = 0) 8 { 9 this->a = a; 10 this->b = b; 11 } 12 int getA() 13 { 14 return a; 15 } 16 int getB() 17 { 18 return b; 19 } 20 friend Complex operator + (const Complex& p1,const Complex& p2); 21 }; 22 Complex operator + (const Complex& p1,const Complex& p2) 23 { 24 Complex ret; 25 ret.a = p1.a + p2.a; 26 ret.b = p1.b + p2.b; 27 return ret; 28 } 29 int main() 30 { 31 Complex c1(1,2); 32 Complex c2(3,4); 33 Complex c3 = c1 + c2; 34 printf("c3.a = %d,c3.b = %d\n",c3.getA(),c3.getB()); 35 return 0; 36 } 37
1 class Type 2 { 3 public: 4 Type operator Sign(const Type&p) 5 { 6 Type ret; 7 return ret; 8 } 9}; 10 #include <stdio.h> 11 class Complex 12 { 13 int a; 14 int b; 15 public: 16 Complex(int a = 0,int b = 0) 17 { 18 this->a = a; 19 this->b = b; 20 } 21 int getA() 22 { 23 return a; 24 } 25 int getB() 26 { 27 return b; 28 } 29 Complex operator + (const Complex& p) 30 { 31 Complex ret; 32 ret.a = this->a + p.a; 33 ret.b = this->b + p.b; 34 return ret; 35 } 36 }; 37 int main() 38 { 39 Complex c1(1,2); 40 Complex c2(3,4); 41 Complex c3 = c1 + c2;//c1.operator + (c2) 42 printf("c3.a = %d,c3.b = %d\n",c3.getA(),c3.getB()); 43 return 0; 44 }
标签:strong 需要 amp 存在 函数重载 形式 int complex opera
原文地址:https://www.cnblogs.com/chengeputongren/p/12176201.html