面向对象程序设计的预习与复习 二 (c++)

运算符重载

基本概念

重载运算符本质上就是将原有的运算符的功能加以扩充,以达到使程序更加简便的目的。

重载运算符的函数

TYPE operator@(形参表) {
//重新定义运算符@的功能
}
operator是关键字。
• @是要被重载的运算符。
• operator@共同组成该运算符函数的名称。
• TYPE是该运算符函数的返回值类型。
eg:
class Complex
{
public:
    double r; //实部
    double i; //虚部
}
Complex operator+(Complex &c1, Complex &c2)
{
    Complex t;
    t.r = c1.r + c2.r;
    t.i = c1.i + c2.i;
    return t;
}
int main()
{
    Complex a(3.0, 4.0), b(10.5, 20.5), c;
    c = a + b;
    cout<<“c: "; c.Print();
}

重载的两种方式:重载为成员函数,重载为友元函数

重载为成员函数

#include <iostream.h>//成员函数
class Complex
{
private:
    double r; //实部
    double i; //虚部
public:
    Complex operator+(const Complex &c);
    Complex operator+(double d);
……
};

Complex Complex::operator+(const Complex &c)
{
    Complex t;
    t.r = r + c.r;
    t.i = i + c.i;
    return t;
}
Complex Complex::operator+(double d)
{
    Complex t;
    t.r = r + d;
    t.i = i;
    return t;
}

int main()
{
    Complex a(3.0, 4.0), b(10.5, 20.5), c, d, e;
    c = a.Add(b);
    d = a + b;
    e = a + 10.5;
    d = a.operator +(b);
    e = a.operator +(10.5);
    c.Print();
    d.Print();
    e.Print();
}

重载为友元函数

friend TYPE operator@(形参表);

双目运算符,形参中有两个参数;单目运算符,形参中有一个参数。

eg:

class Complex
{
public:
    friend Complex operator+(double d, const Complex &c);
    ……
};
Complex operator+(double d, const Complex &c)
{
    Complex t;
    t.r = d + c.r;
    t.i = c.i;
    return t;
}
void main()
{
    Complex a(3.0, 4.0), b(10.5, 20.5), c, d, e;
    e = 10.5 + a;
    ……
}

重载规则

不能定义新的运算符。

.    .*   ::   ?    sizeof  不能重载

当重载为类的成员函数时,运算符重载函数的形参个数要比运算符操作数个数少一个;若重
载为友元函数,则参数个数与操作数个数相同。
“=”、“()”、“[ ]”、“->”只能通过成员函数重载。

不同类型数据件的类型转换

如果想实现自定义类型数据间的类型转换,可以使用转换构成函数,或者运算符重载。

转换构造函数

class Complex
{
private:
    double r;
    double i;
public:
    Complex() { r = i = 0.0; }
    Complex(double d) { r = d; i = 0.0;}
    //Complex(double d1, double d2=0.0) { r = d1; i = d2; } //也可以
    friend Complex operator+(Complex c1, Complex c2);
};

Complex operator+(Complex c1, Complex c2)
{ 
    return Complex(c1.r+c2.r, c1.i+c2.i); 
}
void main()
{
    Complex c1 = Complex(1.2);
    c1 = Complex(1.2);
    Complex c2=5.6;
    c2 = 5.6;
    Complex c3;
    c3 = c1 + 5.6;
    c3 = c1 + Complex(5.6);
    c3 = c1 + (Complex)5.6;    
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值