C++中运算符的操作对象仅限于基本的内置数据类型,而没有办法操作我们自定义的类型(类)。但是大多数时候,我们需要对我们定义的类型执行类似的操作。这时候我们就需要重新定义这个运算符,赋予它新的功能来满足自己的需求。
目录一、有待解决的问题
下面的复数解法可行吗?
我们来看看复数的加法运算:
#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; }输出结果如下:
想
Add函数可以解决复杂对象相加的问题,但复数是真实存在于现实世界中的复数,在数学中的地位和普通实数是一样的。
为什么+运算符不能同时支持复数加法?这涉及到运算符的重载。
第二,操作员超负荷
c++中的重载可以扩展运算符的功能。
运算符的重载是以函数的形式进行的。
自然
用一种特殊形式的函数扩展算子的函数
让我们来探索运算符重载:
#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; }输出结果如下:
运算符重载函数可以定义为类的成员函数。
让我们在成员函数中实现重载操作符:
#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; }输出结果如下:
这说明编译器优先考虑在成员函数中查找运算符重载的函数。
因此,上面的代码可以直接写成:
#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; ret.a = this->a + p.a; ret.b = this->b + p.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; }三。摘要
关于C++操作符重载的文章到此为止。有关C++运算符重载的更多信息,请搜索编程网之前的文章或继续浏览以下相关文章。我希望你将来能支持www.adminjs.cn!