/重载一///
#include <iostream>
#include <cmath>
using namespace std;
class CTriangle
{
public:
CTriangle(void)
{
a=b=c=area=0;
}
explicit CTriangle(float x, float y, float z)
{
float s;
a=x;
b=y; c=z;
s=(a+b+c)/2.0;
area=sqrt(s*(s-a)*(s-b)*(s-c));
}
float Area(void)
{
return this->area;
}
friend CTriangle operator+(CTriangle obj1, CTriangle obj2)
{
CTriangle t(0,0,0);
t.area=obj1.area + obj2.area;
return t;
}
private:
float a,b,c,area;
};
int main(void)
{
CTriangle A(4,4,4), B(5,5,5),D(6,6,6),C;
C=A+B+D; //使用了默认赋值函数,对象内成员将一一对应赋值。
cout<<">>>>>>>>>>>>>"<<C.Area();
return 0;
}
/重载二///
class CExample
{
public:
CExample(int number)
{
a=number;
}
int operator++()//前缀运算符
{
cout<<"++A"<<endl;
++a;
return a;
}
int operator++(int)//后缀运算符
{
cout<<"A++"<<endl;
a++;
return a-1;
}
void display()
{
cout<<"a="<<a<<endl;
}
private:
int a;
};
int main(void)
{
CExample A(0);
A++;
A.display();
++A;
A.display();
return 0;
}
/重载三///
class CPoint
{
public:
CPoint(void)
{
x=y=0;
}
CPoint(int ix, int iy)
{
x=ix;
y=iy;
}
friend bool operator==(CPoint a, CPoint b)
{
if(a.x==b.x && a.y==b.y) return true;
else return false;
}
friend bool operator!=(CPoint a, CPoint b)
{
if(a.x==b.x && a.y==b.y) return false;
return true;
}
friend CPoint operator+(CPoint a, CPoint b)
{
CPoint c;
c.x = a.x+b.x;
c.y = a.y+b.y;
return c;
}
friend CPoint operator-(CPoint a, CPoint b)
{
CPoint c;
c.x = a.x-b.x;
c.y = a.y-b.y;
return c;
}
void operator+=(CPoint b)
{
this->x+=b.x;
this->y+=b.y;
}
void operator-=(CPoint b)
{
this->x-=b.x;
this->y-=b.y;
}
void SetOffset(int ix, int iy)
{
x+=ix;
y+=iy;
cout<<"("<<x<<", "<<y<<")"<<endl;
}
void PrintMe(void)
{
cout<<"("<<x<<", "<<y<<")"<<endl;
}
private:
int x,y;
};
int main(void)
{
CPoint A(0,0) , B(1,1),C(2,2),D(3,3),E(4,4);
CPoint X;
X=A+B;
X.PrintMe();
X=A-B;
X.PrintMe();
cout<<"A==B:"<<(A==B)<<endl;
cout<<"X==B:"<<(A==B)<<endl;
cout<<"A!=B:"<<(X!=B)<<endl;
cout<<"X!=B:"<<(X!=B)<<endl;
A.SetOffset(1,1);
return 0;
}