运算符重载是很重要的,特别是在有些stl中必需重载小于号才能使用。
还有就是输出流的"<<"重载,方便直接cout输出,但是只能有友元函数来重载,因为在cout<<class T <<endl;中其左边类型已经被确定了,必需有这样的友元函数来实现:friend ostream &operator<<(ostream &,Complex &);
详见代码(复数类的实例):
View Code
#include <iostream> #include <cmath> using namespace std; class Complex { private: double real, image ; public: Complex(double r=0.0, double i=0.0) : real(r), image(i) {} Complex(Complex &com) { real = com.real; image = com.image; } void Print() { cout<<"real="<<real<<'\t'<<"image="<<image<<'\n'; } Complex operator+(Complex); // 重载+运算符函数 Complex operator+(double); // 重载+运算符函数 Complex operator=(Complex); // 重载=运算符函数 Complex operator+=(Complex); // 重载+=运算符函数 double abs(void); //求绝对值函数 Complex operator*(Complex); // 重载*运算符函数 Complex operator/(Complex); // 重载/运算符函数 bool operator<(Complex); bool operator>(Complex); friend ostream &operator<<(ostream &,Complex &); // operation+说明为类Complex类的友元函数, // friend只用于类说明中,定义时不加friend friend Complex operator+(double, Complex);//***友元 }; ostream &operator<<(ostream &output,Complex &c) { output << c.real << "," << c.image ; return output; } //注意友元不是成员函数,但以直接访问私有成员 Complex operator + (double d, Complex c) { return Complex(d + c.real, c.image); } Complex Complex::operator+(Complex c) { //重载+ Complex temp(real + c.real, image + c.image) ; return temp; } Complex Complex::operator+(double d) { //重载+ return Complex(real + d, image); } Complex Complex::operator+=(Complex c) {//重载+ = Complex temp; //为了返回Complex类型的值,使+=可以连续使用 temp.real = real + c.real; temp.image = image + c.image; real = temp.real; image = temp.image; return temp; } Complex Complex::operator=(Complex c) {//重载= Complex temp; //定义temp为可返回Complex类型值,使=可连续使用 temp.real = c.real; temp.image = c.image; real = temp.real; image = temp.image; return temp; } double Complex::abs() {//求绝对值函数 return sqrt(real * real + image * image); } Complex Complex::operator*(Complex c) {//重载* return Complex(real*c.real-image*c.image, real*c.image+c.real*image); } Complex Complex::operator/(Complex c) { //重载/ double d = c.real *c.real + c.image * c.image ; return Complex((real * c.real + image * c.image) / d , (image * c.real - real * c.image) / d); } bool Complex::operator<(Complex c) { return abs() < c.abs(); } bool Complex::operator>(Complex c) { return abs() > c.abs(); } int main() { Complex c1(1.0,1.0), c2(2.0,2.0), c3(4.0,4.0), c; double d = 0.5 ; c1.Print(); c=c2+c3; c.Print(); c+=c1; c.Print(); c=c+d; c.Print(); //可用0.5代替d c=c3*c2; c.Print(); c=c3/c1; c.Print(); std::cout<<"c3的模为:"<<c3.abs()<<std::endl; c=c3=c2=c1; c.Print(); //连续赋值 c+=c3+=c2+=c1; c.Print(); //连续加赋值 if(c > c1) cout<<"ok"<<endl; cout << c << endl; c=d+c; return 0; }