1. 基本概念
所谓重载,就是重新赋予新的含义。不仅函数可以重载,运算符也可以重载。
运算符重载的本质是一个函数。
接下来我们来推演一下运算符重载函数进化为成员函数的过程:
1)相加函数作为普通函数
class Complex { public: int a, b; public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } }; Complex Add(Complex &c1, Complex &c2) { Complex tmp(c1.a + c2.a, c1.b + c2.b); return tmp; } int main() { Complex c1(1, 2), c2(3, 4); // 1 普通函数 Complex c3 = Add(c1, c2); return 0; }
2)相加函数作为友元函数
class Complex { public: int a, b; friend Complex operator+(Complex &c1, Complex &c2); public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } }; Complex operator+(Complex &c1, Complex &c2) { Complex tmp(c1.a + c2.a, c1.b + c2.b); return tmp; } int main() { Complex c1(1, 2), c2(3, 4); // 2 友元函数 Complex c3 = operator+(c1, c2); return 0; }
3)相加函数作为类成员函数
class Complex { public: int a, b; Complex operator+(Complex &c2) { Complex tmp; tmp.a = this->a + c2.a ; tmp.b = this->b + c2.b ; return tmp; } public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } }; int main() { Complex c1(1, 2), c2(3, 4); // 3 成员函数 Complex c3 = c1 + c2; return 0; }
未完待续。。。。。。
原文:https://www.cnblogs.com/yanghh/p/12945941.html