第三十讲 运算符重载
运算符它本质上是函数,
(一种特殊的函数,运算符函数)
函数的重载和运算符的重载本质上是一样的
定义:以函数的形式,重写运算符代码,实现新的运算功能
格式:函数类型 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();
}