运算符重载

1. 运算符重载函数作为类的成员函数

例:重载运算符“+”使之适用于两个复数相加

#incllude 
using namespace std;
class Complex
{
public:
    Complex(){real-0;imag=0;}
    Complex(double r,double i){real=r;imag=i;}
    Complex operator+(Complex &c2);//声明重载运算符+的函数
    void display();
privete:
    double r;
    double i;
}
Complex Complex::operator+(Complex &c2)
{
    Complex c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}

void Complex::display()
{
    cout<<"("<<real<<","<"i)"<int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    c3=c1+c2;
    c3.display();
}

结果:(8,-6i)

  • C++编译系统将程序中c1+c2解释为c1.operator+(c2)。

2. 运算符重载函数作为类的友元函数

例:

#incllude 
using namespace std;
class Complex
{
public:
    Complex(){real-0;imag=0;}
    Complex(double r,double i){real=r;imag=i;}
    friend Complex operator+(Complex &c1,Complex &c2);//声明重载运算符+的函数
    void display();
privete:
    double r;
    double i;
}
Complex operator+(Complex &c1,Complex &c2)
{
    return Complex(c1.real+c2.real.c1.img+c2.imag);
}

void Complex::display()
{
    cout<<"("<","<"i)"<int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    c3=c1+c2;
    c3.display();
}
  • 在将运算符+重载为非成员函数后,C++编译系统将程序中c1+c2解释为operator+(c1+c2)。

问:什么时候该用成员函数方式?什么时候该用友元函数方式?二者有何区别?
答:如果将运算符重载为类的成员函数,它可以通过this指针自由的访问本类的数据成员,因此可以少些一个函数参数。但必须要求运算表达式的第一个参数(即运算符左侧的操作数)是一个类的对象,而且与运算符函数的类型相同。因为必须通过类的对象调用该类的成员函数,而且只有运算符重载函数返回值与该对象同型,运算结果才有意义。
如果出于某种考虑,要求使用重载运算符时左侧的操作数是整型量(如表达式i+c2,运算符左侧的操作数i是整数),这是无法利用前面定义为类的成员函数的重载运算符的,必须重新声明重载运算符函数为类的友元函数:
friend Complex operator+(int &i,Complex &c);
注意在使用运算符表达式时候参数类型要匹配。如:
c3=i+c2//正确,类型匹配
c3=c2+i//错误,类型不匹配
如果希望使用交换律,则应再一次重载运算符“+”。如:
friend Complex operator+(Complex &c,int &i);

3. 重载单目运算符

例:重载前置自增运算符“++”

#include 
using namespace std;
class Time
{
public:
    ......
    Time operator++();//声明运算符重载函数
private:
    ......
}
Time Time::operator++()
{
    if(++sec>=60)
    {
        sec-=60;
        ++minute;
        return *this;
    }
}
  • C++约定:如果在自增(自减)运算符重载函数中,增加一个int形参,就是后置自增(自减)运算符函数。

4.重载流插入运算符

#include 
using namespace std;
class Complex
{
public:
    Complex(){real-0;imag=0;}
    Complex(double r,double i){real=r;imag=i;}
    Complex operator+(Complex &c2);//声明重载运算符+的函数
    friend ostream& operator << (ostream&,complex&);
privete:
    double r;
    double i;
}
Complex Complex::operator+(Complex &c2)
{
    Complex c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}

ostream& operator << (ostream& output,Complex& c)
{
    output<<"("<"+"<"i)"<int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    c3=c1+c2;
    cout<
  • return output的作用是能连续向输出流插入信息。
  • 只能将重载“>>”和“<<”的函数作为友元函数或普通函数,而不能定义为成员函数。
  • C++规定运算符“<<”重载函数的第一个参数和函数的类型都必须是ostream类型的引用,为了返回cout当前的值以便连续输出。

你可能感兴趣的:(C++运算符重载,C++)