设为首页 加入收藏

TOP

重载操作符 'operator'
2019-01-19 00:08:34 】 浏览:77
Tags:重载 操作 ' operator'

operatorC++ 的(运算符的)重载操作符。用作扩展运算符的功能。

它和运算符一起使用,表示一个运算符函数,理解时应将  【operator+运算符】 整体上视为一个函数名。

要注意的是:一方面要使运算符的使用方法与其原来一致,另一方面扩展其功能只能通过函数的方式(c++中,“功能”都是由函数实现的)。

 

使用时:

【返回类型】 【operator+运算符】 (const ElemType&a)const  {...}

 

为什么需要重载操作符?

系统的所有操作符,一般情况下,只支持基本数据类型和标准库中提供的class。

而针对用户自己定义的类型,如果需要其支持基本操作,如’+’,‘-’,‘*’,‘/’,‘==’等等,则需要用户自己来定义实现(重载)这个操作符在此新类型的具体实现。

 

例:

创建一个point类并重载‘+’,‘-’运算符;

struct point
{
    double x;
    double y;
    point() {};
    //初始化
    point(double a,double b)
    {
        x = a;
        y = b;
    };
    //重载+运算符
    point operator + (const point& a) const
    {
        return point (x+ a.x, y+ a.y);
    }
    //重载-运算符
    point operator - (const point& a)const
    {
        return point(x-a.x, y-a.y);
    }
};

 

检验;

int main()
{
    point w(2, 6), v(5, 3);
    printf("w与v的坐标分别为:\n");
    printf("w = (%.2f, %.2f)\nv = (%.2f, %.2f)\n", w.x, w.y, v.x, v.y);
    point z = w+ v;
    printf("w+v 的值z = (%.2f, %.2f)\n", z.x, z.y);
    z = w- v;
    printf("w-v 的值z = (%.2f, %.2f)\n", z.x, z.y);
    return 0;
}

 

检验结果;

 

end;

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇BZOJ2337: [HNOI2011]XOR和路径(.. 下一篇Linux下QT、cannot find -lGL、

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目