C++中的函数重载

C++ 中的运算符重载 

你可以重新定义或重载的大部分 C++ 已有的操作符。因此,程序员可以像使用用户自定义类型一样使用操作符。 

重载操作符是一类函数,它们就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。像任何其它函数,重载运算符也有返回类型和参数列表。

Box operator+(const Box&);

声明加法运算符可以用来使两个 Box 对象相加并返回最终 Box 对象。大多数重载运算符可以被定义为普通非成员函数或类成员函数。如果我们把上面的函数定义为一个类的非成员函数,那么我们就必须为每个操作数传两个参数如下:

    Box operator+(const Box&, const Box&);

下面是通过使用成员函数来展示运算符重载的概念的示例。这里一个对象作为一个参数被传递,通过访问这个对象可以获得参数的属性,将调用这个操作符的对象可以通过使用 this 操作符获得,下面这个例子展示了这一点:

#include<bits/stdc++.h>
using namespace std;
class Box
{
    public :
        double getVolume(void)
        {
            return length * breadth * height;
        }
        void setLength(double len)
        {
            length = len;
        }
        void setBreadth(double bre)
        {
            breadth = bre;
        }
        void setHeight( double hei )
        {
            height = hei;
        }
        Box operator + (const Box &other)//第一种重载方式
        {
            Box box;
            box.length = this->length + other.length;
            box.breadth = this->breadth + other.breadth;
            box.height = this->height + other.height;
            return box;
        }
    public:
        double length;
        double breadth;
        double height;
};
Box operator + (const Box &ths, const Box &other)//第二种重载方式
{
    Box box;
    box.length = ths.length + other.length;
    box.breadth = ths.breadth + other.breadth;
    box.height = ths.height + other.height;
    return box;
}
int main()
{
    Box Box1, Box2, Box3;
    double volume = 0;
    Box1.setLength(6.0);
    Box1.setBreadth(7.0);
    Box1.setHeight(5.0);

    Box2.setLength(12.0);
    Box2.setBreadth(13.0);
    Box2.setHeight(10.0);

    volume = Box1.getVolume();
    cout << "Volume of Box1 : " << volume <<endl;

    // volume of box 2
    volume = Box2.getVolume();
    cout << "Volume of Box2 : " << volume <<endl;

    // Add two object as follows:
    Box3 = Box1 + Box2;

    // volume of box 3
    volume = Box3.getVolume();
    cout << "Volume of Box3 : " << volume <<endl;
    return 0;
}

上面的代码编译和执行时,它产生以下结果:

    Volume of Box1 : 210
    Volume of Box2 : 1560
    Volume of Box3 : 5400

可重载/不可重载的运算符

下面这张表列举了可以重载的运算符:

+-*/%^
&|~!,=
<><=>=++--
<<>>==!=&&||
+=-=/=%=^=&=
|=*=<<=>>=[ ]()
->->*newnew[ ]deletedelete[ ]

下面这张表列举了不可以重载的运算符:

::.*.?:

运算符重载例子

这里有各种操作符重载的例子来帮助你理解这一概念。

序号 运算符和例子
1一元运算符重载
2二元运算符重载
3关系运算符重载
4输入/输出运算符重载
5++ 和 -- 运算符重载
6赋值运算符重载
7函数 call() 运算符重载
8下标[ ]运算符重载
9类成员获取运算符 -< 重载
来源: http://wiki.jikexueyuan.com/project/cplusplus/overloading.html
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值