1.三角形面积(构造函数)
#include<iostream>
using namespace std;
class Tra
{
private:double A,B,C,p,s;
public:Tra(double a,double b,double c);
void display();
};
Tra::Tra(double a,double b,double c)
{
A=a;
B=b;
C=c;
}
void Tra::display()
{
p=(A+B+C)/2;
s=sqrt(p*(p-A)*(p-B)*(p-C));
cout<<s<<endl;
}
int main()
{
Tra s(3,4,5);
s.display();
return 0;
}
2.求线段长度和中点坐标(构造函数)
#include<iostream>
using namespace std;
class L
{
private:double x1,x2,y1,y2;
public:
L(double a,double b,double c,double d);
void display();
};
L::L(double a,double b,double c,double d)
{
x1=a;
x2=b;
y1=c;
y2=d;
}
void L::display()
{
double l;
l=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
cout<<"线段长度为:"<<l<<endl;
cout<<"中点坐标为:("<<(x1+x2)/2<<","<<(y1+y2)/2<<")"<<endl;
}
int main()
{
L p(0,1,0,1);
p.display();
return 0;
}
3.求线段长度和中点坐标(点类、线类)
#include<iostream>
using namespace std;
class point
{
private:double x,y;
public:point(double x1,double y1)
{
x=x1;
y=y1;
}
double getx(){return x;}
double gety(){return y;}
};
class L
{
private:point p1,p2;
public:L(double x1,double y1,double x2,double y2):p1(x1,y1),p2(x2,y2){}
void mid_point()
{
double x,y;
x=(p1.getx()+p2.getx())/2;
y=(p1.gety()+p2.gety())/2;
cout<<"中点坐标为:("<<x<<","<<y<<")"<<endl;
}
void lenth_point()
{
double len;
len=sqrt((p1.getx()-p2.getx())*(p1.getx()-p2.getx())+(p1.gety()-p2.gety())*(p1.gety()-p2.gety()));
cout<<"线段长度为:"<<len<<endl;
}
};
int main()
{
L l(0,0,1,1);
l.mid_point();
l.lenth_point();
return 0;
}
4.求线段长度和中点坐标(继承)
#include<iostream>
using namespace std;
class point
{
private:double x,y;
public:
point(double a,double b)
{x=a;y=b;}
double getx(){return x;}
double gety(){return y;}
};
class line:public point
{
private:double m,n;
public:line(double a,double b,double c,double d):point(a,b){m=c,n=d;}
void f1()
{
double d;
d=sqrt((getx()-m)*(getx()-m)+(gety()-n)*(gety()-n));
cout<<"线段长度:"<<d<<endl;
}
void f2()
{
cout<<"中点坐标:("<<(getx()+m)/2<<","<<(gety()+n)/2<<")"<<endl;
}
};
int main()
{
line l(0,0,1,1);
l.f1();
l.f2();
return 0;
}
5.矩阵相加
#include<iostream>
using namespace std;
class M
{
private:int s[2][3];
public:
friend M operator+(M & a,M & b);
friend istream & operator >>(istream & in,M & c);
friend ostream & operator <<(ostream &out,M & c);
};
M operator+(M & a,M & b)
{
M temp;
int i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
temp.s[i][j]=a.s[i][j]+b.s[i][j];
return temp;
}
istream & operator >>(istream & in,M & c)
{
int i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
in>>c.s[i][j];
return in;
}
ostream & operator <<(ostream &out,M & c)
{
int i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
out<<c.s[i][j];
return out;
}
int main()
{
M a,b,c;
cin>>a;
cin>>b;
c=a+b;
cout<<c<<endl;
return 0;
}