重载操作符 'operator'

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

它和运算符一起使用,表示一个运算符函数,理解时应将  【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;

猜你喜欢

转载自www.cnblogs.com/Amaris-diana/p/10289937.html