基类为平面点类(命名为:Point),有一个点的坐标(x1,y1)。派生类为线段类(命名为:Line),有一个点的坐标(x2,y2)。派生类中的线段以基类中的数据作为起点,自己类中的数据作为终点。两个类分别编写构造函数(重载)对数据进行初始化。
在子类内对“-”(减号)运算符进行重载,两条线段相减后返回新的线段,新线段的起点是第一条线段的终点,新线段的终点是第二条线段的起点。
在类内对“<<”运算符进行重载(使用友元),输出子类对象的数据。在主函数中定义两个子类对象,相“-”后使用“<<”输出数据。
#include<iostream>
using namespace std;
class Point
{
protected:
int x1;
int y1;
public:
Point(int xx1,int yy1)
{
x1=xx1;
y1=yy1;
}
Point()
{
x1=1;
y1=1;
}
};
class Line:public Point
{
private:
int x2;
int y2;
public:
Line(int xx1,int yy1,int xx2,int yy2):Point(xx1,yy1)
{
x2=xx2;
y2=yy2;
}
Line():Point()//注意要用两种方式进行初始化,后面方便设成员
{
x2=1;
y2=1;
}
void output()
{
cout<<"起点:"<<"("<<x1<<","<<y1<<")"<<endl;
cout<<"终点:"<<"("<<x2<<","<<y2<<")"<<endl;
}
Line operator-(Line l)//括号里的是第二条线段位于减号后面。类里原有的线段是第一条线段位于减号前面
{
Line t;
t.x1=x2;
t.y1=y2;
t.x2=l.x1;
t.y2=l.y1;
return t;
}
friend ostream& operator<<(ostream& os,Line l)
{
l.output();
return os;
}
};
int main()
{
Line l1(1,2,3,4);
Line l2(5,6,7,8);
Line l3;
l3=l1-l2;
cout<<l1<<endl;
cout<<l2<<endl;
cout<<l3<<endl;
return 0;
}
“>”的重载
bool operator >(A a)
{
if(a.n<n)
return true;
else
return false;
}