C++——运算符重载

  • 多态:同样的消息被不同类型的对象接收时导致完全不同的行为。

  • 多态分为编译时的多态和运行时的多态。

  • 联编:确定操作的具体对象的过程。分静态联编和动态联编。

  • 静态联编——编译和链接时进行如函数的重载、函数模板的实例化。

  • 动态联编——运行时进行,通过虚函数。

运算符重载

  • 不可重载的运算符(5个):  .    .*    ::    ?:    sizeof
  • 重载一般有两种形式:类的成员函数和非成员函数
  • 成员函数运算符与友元函数运算符具有一些各自的特点:
  1. 一般单目运算符最好重载为成员函数,双目为友元函数
  2. 有一些双目不能重载为友元,如:= ,(), [ ],->
  3. 类型转化函数只能定义为类的成员函数。
  4. 若需修改对象的状态,最好为成员函数。
  5. 若操作符所需的操作数(特别是第一个)希望有隐式类型转换,则只能选用友元函数。
  6. 当重载为成员函数时,最左边的操作数必须是一个类对象。否则重载为友元函数。
  7. 当重载运算符的运算是可交换时,重载为友元函数。
  • ++、+、-、=、->的重载:
class Complex 
{
private:
    double real,image;
    Complex *PC;
public:
    Complex(Complex * PC = NULL)
    {
        this->PC = PC;
    }
    Complex(double real = 0, double image = 0)
    {
        this->real = real;
        this->image = image;
    }
    void display()
    {
        cout << "(" << real << "," << image << ")" << endl;
    }
    friend Complex operator + (Complex A, Complex B);
    Complex operator - (Complex B);
    Complex operator = (Complex B);
    Complex operator - ();//负号;
    Complex operator ++ ();
    Complex operator ++ (int);
    Complex * operator -> ();
};
Complex Complex::operator + (Complex A, Complex B)
{
    return Complex(A.real+B.real,A.image+B.image);
}
Complex Complex::operator-(Complex B)
{
    return Complex(real-B-real,image-B.image);
}
Complex Complex::operator=(Complex B)
{
    real = B.real;
    image = B.image;
    return *this;
}
Complex Complex::operator - ()
{
    return Complex(-real,-image);
}
Complex Complex::operator ++()
{
    return Complex(++real,++image);
}
Complex Complex::operator ++ (int)
{
    return Complex(real++,image);
}
Complex * Complex::operator -> ()
{
    static Complex NullComplex(0,0);
    if(PC == NULL)
        return &NullComplex;
    return PC;
}
  • [ ]运算符的重载:
class String
{
private:
    char str;
    int len;
public:
    char &operator [] (int n)
    {
        return *(str+n);
    }
    const char &operator[] (int n) const
    {
        return *(str+n);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值