Comlpex.h 源码
#ifndef _COMPLEX_H_ #define _COMPLEX_H_ class Complex { double a; double b; public: Complex(double a = 0, double b = 0); double getA(); double getB(); double modulus(const Complex& c); Complex operator + (const Complex& c); Complex operator - (const Complex& c); Complex operator * (const Complex& c); Complex operator / (const Complex& c); bool operator == (const Complex& c); bool operator != (const Complex& c); Complex& operator = (const Complex& c); }; #endif
Complex.cpp 源码
#include "Complex.h" #include <math.h> Complex::Complex(double a, double b) { this->a = a; this->b = b; } double Complex::getA() { return a; } double Complex::getB() { return b; } double Complex::modulus(const Complex& c) { return sqrt(a * a + b * b); } Complex Complex::operator + (const Complex& c) { double na = a + c.a; double nb = b + c.b; Complex ret(na, nb); return ret; } Complex Complex::operator - (const Complex& c) { double na = a - c.a; double nb = b - c.b; Complex ret(na, nb); return ret; } Complex Complex::operator * (const Complex& c) { double na = a * c.a - b * c.b; double nb = a * c.b + b * c.a; Complex ret(na, nb); return ret; } Complex Complex::operator / (const Complex& c) { double cm = c.a * c.a + c.b * c.b; double na = (a * c.a + b * c.b) / cm; double nb = (b * c.a - a * c.b) / cm; Complex ret(na, nb); return ret; } bool Complex::operator == (const Complex& c) { return (a == c.a) && (b == c.b); } bool Complex::operator != (const Complex& c) { return !(*this == c); } Complex& Complex::operator = (const Complex& c) { if( this != &c ) { a = c.a; b = c.b; } return *this; }
test.cpp 源码
#include <stdio.h> #include "Complex.h" int main() { Complex c1(1, 2); Complex c2(3, 4); Complex c3 = c2 - c1; Complex c4 = c1 * c3; Complex c5 = c2 / c1; printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB()); printf("c4.a = %f, c4.b = %f\n", c4.getA(), c4.getB()); printf("c5.a = %f, c5.b = %f\n", c5.getA(), c5.getB()); Complex c6(2, 2); printf("c3 == c6 : %d\n", c3 == c6); printf("c3 != c4 : %d\n", c3 != c4); (c3 = c2) = c1; printf("c1.a = %f, c1.b = %f\n", c1.getA(), c1.getB()); printf("c2.a = %f, c2.b = %f\n", c2.getA(), c2.getB()); printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB()); return 0; }
我们在 test.cpp 中定义了两个复数,再接着利用相关操作定义了三个复数,在第 16 行定义的复数 c6,我们用口算都知道它和 c3 相等了,所以第 18 行会打印出 1,第 19 行也会打印出 1。第 21 行进行的赋值操作,先是将 c2 赋值给 c3,然后再将 c1 赋值给它们的结果,也就是最后的结果是将 c1 赋值给 c3。我们看看编译结果是否如我们所分析的那样
我们看到编译的结果和我们所分析的是一致的,至于乘法和除法的相关操作,我们可以自己去手动计算下,看看实现是否正确。
我们在实现操作符重载的时候得注意:a> C++ 规定赋值操作符(=)只能重载为成员函数;b> 操作符重载不能改变原操作符的优先级;c> 操作符不能改变操作数的个数;d> 操作符重载不应改变操作符的原有语义。
通过对复数类的完善的学习,总结如下:1、复数的概念可以通过自定义类实现;2、复数中的运算符操作可以通过操作符重载实现;3、赋值操作符只能通过成员函数实现;4、操作符重载的本质为函数定义。
欢迎大家一起来学习 C++ 语言,可以加我QQ:243343083。
原文地址:http://blog.51cto.com/12810168/2118864