您的位置:首页 > 编程语言 > C语言/C++

C++ 操作符重载

2013-10-11 19:59 337 查看
1、为什么要使用操作符重载?

操作符和方法在本质上一样,使用操作符更符合人性化的描述。

2、操作符重载分为 普通操作符重载和成员操作符重载,区别在于:

  a、普通操作符重载要访问对象的私有成员,因此要设计为friend,而成员操作符重载不需要;

  b、相比于普通操作符重载,成员操作符重载,少了一个形参,因为成员方法总是与对象绑定使用的,被绑定的对象就是操作符的第一个参数;

示例代码:

#include "StdAfx.h"
#include <iostream>
#include "Point.h"

Point ::Point()
{
}

Point::Point(int x,int y)
{
this->x = x;
this->y = y;
}

void Point::Print()const
{
std::cout<<"X:"<<x<<" Y:"<<y<<std::endl;
}

Point operator+(const Point& a,const Point& b)
{
Point s(a.x+b.x,a.y+b.y);

return s;
}

Point operator+(const Point& a,int b)
{
Point s(a.x+b,a.y+b);

return s;
}

void Point::Set(int x,int y)
{
this->x = x;
this->y = y;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: