操作符的重载有一些规则:
1. 重载操作符必须具有一个类类型或枚举类型操作数。这条规则强制重载操作符不能重新定义用于内置类型对象的操作符的含义。
如: int operator+(int, int), 不可以
2. 为类设计重载操作符的时候,必须选择是将操作符设置为类成员还是普通非成员函数。在某些情况下,程序没有选择,操作符必须是成员;在另外一些情况下,有些经验可以指导我们做出决定。下面是一些指导:
a. 赋值(=),下标([]),调用(())和成员访问箭头(->)等操作符必须定义为成员,将这些操作符定义为非成员函数将在编译时标记为错误。
b. 像赋值一样,复合赋值操作符通常应定义为类的成员。与赋值不同的是,不一定非得这样做,如果定义为非成员复合赋值操作符,不会出现编译错误。
c. 改变对象状态或与给定类型紧密联系的其他一些操作符,如自增,自减和解引用,通常应定义为类成员。
d 对称的操作符,如算术操作符,相等操作符,关系操作符和位操作符,最好定义为普通非成员函数。
e io操作符必须定义为非成员函数,重载为类的友元。
例子:
complex0.h
#ifndef COMPLEX0_H_
#define COMPLEX0_H_
#include<iostream>
class complex
{
private:
double x;
double y;
public:
complex();
complex(double a,double b);
complex operator+(complex &c) const;
complex operator-(complex &c) const;
complex operator*(complex &c) const;
complex operator~();
friend complex operator*(double n,complex &c);
friend std::ostream & operator<<(std::ostream &os,const complex &c);
friend std::istream & operator>>(std::istream &os,complex &c);
};
#endif
complex0.cpp
#include<iostream>
#include"complex0.h"
using namespace std;
complex::complex()
{
x=y=0;
}
complex::complex(double a,double b)
{
x=a;
y=b;
}
complex complex::operator+(complex &c) const
{
complex com;
com.x=x+c.x;
com.y=y+c.y;
return com;
}
complex complex::operator-(complex &c) const
{
complex com;
com.x=x-c.x;
com.y=y-c.y;
return com;
}
complex complex::operator*(complex &c) const
{
complex com;
com.x=x*c.x-y*c.y;
com.y=x*c.y+y*c.x;
return com;
}
complex operator*(double n,complex &c)
{
complex com;
com.x=n*c.x;
com.y=n*c.y;
return com;
}
complex complex::operator~()
{
return complex(x,-y);
}
std::ostream & operator<<(std::ostream &os,const complex &c)
{
cout<<"("<<c.x<<","<<c.y<<"i)"<<endl;
return os;
}
std::istream & operator>>(std::istream &os,complex &c)
{
cin>>c.x>>c.y;
return os;
}
complex.cpp
#include<iostream>
using namespace std;
#include"complex0.h"
int main()
{
complex a(3.0,4.0);
complex c;
cout<<"Enter a complex number (q to quit):\n";
while(cin>>c)
{
cout<<"c is "<<c<<endl;
cout<<"complex conjugate is "<<~c<<endl;
cout<<"a is "<<a<<endl;
cout<<"a+c is "<<a+c<<endl;
cout<<"a-c is "<<a-c<<endl;
cout<<"a*c is "<<a*c<<endl;
cout<<"2*c is "<<2*c<<endl;
cout<<"Enter a complex number (q to quit):\n";
}
cout<<"Done\n";
return 0;
}