阿牛哥C++笔记---5

第三十讲 运算符重载

运算符它本质上是函数,
(一种特殊的函数,运算符函数)

函数的重载和运算符的重载本质上是一样的
定义:以函数的形式,重写运算符代码,实现新的运算功能
格式:函数类型 operator运算符();
功能:实现对象或者对象之间的运算
如:向量相加减,复数相加减运算

如果x,y是两个对象或者变量,+不是对象的成员,则z=z+y;相当于:

z=operate+(x,y);
如果x,y是两个对象,+是对象的成员,则:z=x+y;相当于:

z=x.operate+(y);
注意:参数的个数少一个;隐式了一个参数,已在对象中

第三十一讲 实验 运算符重载

掌握运算符重载的方法
当运算符是成员函数时
当运算符不是成员函数时

//运算符不是成员函数的实验,
#include <iostream.h>

class CVector
{
public:
 CVector();
 CVector(int x,int y);
 friend CVector operator+(CVector v1,CVector v2);
 void output();
private:
 int x;
 int y;

};

CVector::CVector()
{
 x = 0;
 y = 0;
}

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

void CVector::output()
{
 cout<<this->x<<","<<this->y<<endl;
}

CVector operator+(CVector v1,CVector v2)
{
 CVector temp;
 temp.x = v1.x + v2.x;
 temp.y = v1.y + v2.y;
 return temp;
}
void main()
{
 CVector v1(1,2),v2(2,3),v3;
 //v3 = v1 + v2;//和下面的效果相同,运算符的重载,很直观


 v3 = operator+(v1,v2);
 v3.output();
}

//是成员函数的运算符重载 
#include <iostream.h>

class CVector
{
public:
 CVector();
 CVector(int x,int y);
 CVector operator+(CVector v);//在这隐式为这样,本是

CVector operator+(CVector this, CVector y)
 void output();
private:
 int x;
 int y;

};

CVector::CVector()
{
 x = 0;
 y = 0;
}

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

void CVector::output()
{
 cout<<this->x<<","<<this->y<<endl;
}

CVector CVector::operator+(CVector v)
{
 CVector tmp;
 tmp.x = this->x + v.x;
 tmp.y = this->y + v.y;
 return tmp;
}

void main()
{
 CVector v1(1,2),v2(2,3),v3;
 v3 = v1 + v2;//
 v3 = v1.operator + (v2);
 v3.output();
 
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值