运算符重载
对四则运算符,加减乘除进行重载
对+进行重载
Fraction operator +(Fraction& a1)
{
Fraction b1;
b1.fm = a1.fm + fm;
return b1;
};
对-进行重载
Fraction operator-(Fraction& a1)
{
Fraction b1;
b1.fm = a1.fm - fm;
return b1;
};
对*进行重载
Fraction operator*(Fraction& a1)
{
Fraction b1;
int m, z;
b1.fm = a1.fm * fm;
return b1;
};
对/进行重载
Fraction operator/(Fraction& a1)
{
Fraction b1;
int m, z;
b1.fm = fm / a1.fm;
return b1;
};
对=进行重载
一般情况下不考虑对=的重载,但是如果牵扯到动态分配空间,就需要对=进行重载,因为如果不对=进行重载的话,就是浅拷贝;对=进行重载了,才是深拷贝
CArray operator =(const CArray& a)
{
n = a.n;
m = a.m;
data = new int* [n];
for (int i = 0; i < n; i++)
data[i] = new int[m];
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; j++)
data[i][j] = a.data[i][j];
return *this;
}
对++、--进行重载
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Fraction {
protected:
int x, y, z;
public:
Fraction() {};
Fraction(int xx,int yy,int zz)
{
x = xx;
y = yy;
z = zz;
}
对++进行重载
friend Fraction operator ++(Fraction& a1)//前置++
{
Fraction c1;
c1.x = ++a1.x;
c1.y = ++a1.y;
c1.z = ++a1.z;
return c1;
};
friend Fraction operator ++(Fraction& a1,int)//后置++
{
Fraction c1;
c1.x = a1.x++;
c1.y = a1.y++;
c1.z = a1.z++;
return c1;
};
对--进行重载
friend Fraction operator --(Fraction& a1)//前置--
{
Fraction c1;
c1.x = --a1.x;
c1.y = --a1.y;
c1.z = --a1.z;
return c1;
};
friend Fraction operator --(Fraction& a1,int)//后置--
{
Fraction c1;
c1.x = a1.x--;
c1.y = a1.y--;
c1.z = a1.z--;
return c1;
};
对>、<、==进行重载
#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
class CPoint {
protected:
int x;
int y;
public:
CPoint() {};
CPoint(int xx, int yy)
{
x = xx;
y = yy;
}
对>进行重载
bool operator>(CRectangle& p)
{
if (p.xl >= xl && p.xr <= xr && p.yl <= yl && p.yr >= yr)
return true;
else
return false;
}
对<进行重载
bool operator>(CRectangle& p)
{
if (p.xl < xl && p.xr < xr && p.yl < yl && p.yr < yr)
return true;
else
return false;
}
对==进行重载
bool operator==(CRectangle& p)
{
if (p.xl == xl && p.xr == xr && p.yl == yl && p.yr == yr)
return true;
else
return false;
}
对IO的>>和<<进行重载
#include<iostream>
#include<string>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
class RMB {
protected:
int y;
int j;
int f;
float m;
public:
RMB() {
y = 0;
j = 0;
f = 0;
m = 0;
};
RMB(float mm)
{
m = mm;
y = int(m);
f = (m - y)*100;
f = f % 10;
j = (m - y) * 100 - f;
j = j / 10;
}
对>>进行重载
friend istream& operator>>(istream& is, RMB& r)
{
is >> r.y >> r.j >> r.f;
return is;
}
对<<进行重载
friend ostream& operator << (ostream& os, RMB& r)
{
os << r.y << "元" << r.j << "角" << r.f<<"分";
return os;
}
对int()进行重载
operator int()
{
return (xr-xl)*(yl-yr);
}
对下标运算符进行重载
对[]进行重载
int* operator [](int k)
{
return data[k];
}
对()进行重载
int operator () (int i, int j)
{
return data[i][j];
}