操作符重载很早前就学过,现在重温下,又有更深一层的体会。新建控制台程序,代码如下:
#include <iostream> using namespace std; class Complex { public: Complex(double r = 0, double i = 0) : _real(r), _imag(i) { } double GetReal() { return _real; } double GetImag() { return _imag; } Complex operator + (Complex&); //函数返回的是一个类,形参(相加的对象)也是一个类 Complex operator - (Complex&); Complex operator + (double); //函数返回的是一个类,形参(相加的对象)是一个double数值 Complex operator - (double); private: double _real, _imag; }; Complex Complex::operator + (Complex& c) { Complex tmp; tmp._real = _real + c._real; tmp._imag = _imag + c._imag; return tmp; } Complex Complex::operator - (Complex& c) { Complex tmp; tmp._real = _real - c._real; tmp._imag = _imag - c._imag; return tmp; } Complex Complex::operator + (double d) { Complex tmp; tmp._real = _real + d; tmp._imag = _imag; return tmp; } Complex Complex::operator - (double d) { Complex tmp; tmp._real = _real - d; tmp._imag = _imag; return tmp; } int main() { Complex c1(3.59, 15.6), c2(32.1, -15.8), c3, c4; c3 = c1 + c2; c4 = c3 - 10.5; cout << c3.GetReal() << ", " << c3.GetImag() << '\t' << c4.GetReal() << ", " << c4.GetImag() << endl; return 0; }重点说明:(截图来自 Visual C++范例大全.pdf)