标签:
1、运算符重载
目的
运算符的重载实质是函数重载,类型如下:
返回值类型 operator 运算符(形参表) { ... }
在程序编译时
运算符重载为普通函数示例:
#include <iostream> using namespace std; class Complex { public: Complex(double r = 0.0, double i = 0.0) { real = r; img = i; } double real; // real part double img; // imaginary part }; Complex operator + (const Complex &a, const Complex &b) { return Complex(a.real+b.real, a.img+b.img); } int main() { Complex a(1, 2), b(2, 3), c; c = a + b; cout << c.real << ":" << c.img << endl; }
这里a+b 就相当于 operator+(a, b);
重载为普通函数时,参数个数为运算符数目。
运算符重载为成员函数示例:(重载为成员函数时,参数个数为运算符数目减一)
#include <iostream> using namespace std; class Complex { public: Complex(double r = 0.0, double i = 0.0) { real = r; img = i; } Complex operator+(const Complex &); // addition Complex operator-(const Complex &); // subtraction double real; // real part double img; // imaginary part }; Complex Complex::operator +(const Complex & operand2) { return Complex(real+operand2.real, img+operand2.img); } Complex Complex::operator -(const Complex & operand2) { return Complex(real-operand2.real, img-operand2.img); } int main() { Complex a(1, 2), b(2, 3), c; c = a + b; cout << c.real << ":" << c.img << endl; c = b - a; cout << c.real << ":" << c.img << endl; }
标签:
原文地址:http://www.cnblogs.com/aqing1987/p/4331136.html