|
一、操作符重载: 1、我们先来看一个问题实现,下面的复数解决方案是否可行,复数大家应该都不陌生(分为实部和虚部): class Complex{ public: int a; int b; }; /*--------------------------*/ int main() { Complex c1 = {1,2}; Complex c2 = {3,4}; Complex c3 = c1 + c2;//也就是复数的实部加实部,虚部叫虚部。 return 0; } 注:成员变量为公有且没有自定义构造函数的时候,可以通过大括号来分别初始 化成员变量; 代码版本一: #include <stdio.h>class Complex { int a; int b; public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } int getA() { return a; } int getB() { return b; } friend Complex Add(const Complex& p1, const Complex& p2); }; Complex Add(const Complex& p1, const Complex& p2) { Complex ret; ret.a = p1.a + p2.a; ret.b = p1.b + p2.b; return ret; } int main() { Complex c1(1, 2); Complex c2(3, 4); Complex c3 = Add(c1, c2); // c1 + c2 printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB()); return 0; } 运行结果: root@txp-virtual-machine:/home/txp# ./a.outc3.a=4,c3,b=6 这里通过Add函数可以解决Complex对象相加的问题,但是在我们数学运算里面就是直接实部加实部,虚部加虚部,和正常的实数相加一样,所以说,为什么不直接这样操作呢,这就涉及到符号"+"的问题。 2、操作重载符的引出
3、操作重载符的语法:
{ Type ret; return ret; } 注:Sign为系统中预定义的操作符,比如:+、-、*、/ 等 代码版本二: #include <stdio.h>class Complex { int a; int b; public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } int getA() { return a; } int getB() { return b; } friend Complex operator + (const Complex& p1, const Complex& p2); }; Complex operator + (const Complex& p1, const Complex& p2) { Complex ret; ret.a = p1.a + p2.a; ret.b = p1.b + p2.b; return ret; } int main() { Complex c1(1, 2); Complex c2(3, 4); Complex c3 = c1 + c2; // operator + (c1, c2) printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB()); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outc3.a=4,c3,b=6 4、再次改进代码:
{ public: Type operator Sign(const Type& p) { Type ret; return ret; } }; 代码版本三: #include <stdio.h>class Complex { int a; int b; public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } int getA() { return a; } int getB() { return b; } Complex operator + (const Complex& p) { Complex ret; printf("Complex operator + (const Complex& p)\n"); ret.a = this->a + p.a; ret.b = this->b + p.b; return ret; } friend Complex operator + (const Complex& p1, const Complex& p2); }; Complex operator + (const Complex& p1, const Complex& p2) { Complex ret; printf("Complex operator + (const Complex& p1, const Complex& p2)\n"); ret.a = p1.a + p2.a; ret.b = p1.b + p2.b; return ret; } int main() { Complex c1(1, 2); Complex c2(3, 4); Complex c3 = c1 + c2; // c1.operator + (c2) printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB()); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outComplex operator +(const Complex& p) c3.a=4,c3,b=6 二、总结:
好了,今天的分享就到这里,如果文章中有错误或者不理解的地方,可以交流互动,一起进步。 |
微信公众号
手机版