1.利用多态性来求四种几何图形的面积之和。这四种几何图形是:三角形、矩形、正方形和圆。几何图形的类型可以通过构造函数或通过成员函数来设置。
#include<iostream>
#include<string> //用到C++的字符串需头文件
#include<cmath> //从C继承的
using namespace std;
#define pi 3.14
class tuxing
{
public:
virtual void tuxing1()=0;
virtual void mianji(double a,double b=1.0,double c=1.0)=0;//因为不同图形所需的参数不同
//在基类里定义了两个纯虚函数,子类必须重写这两个函数
};
class sanjiao:public tuxing
{
public:
void tuxing1()
{
cout<<"图形是三角形"<<endl;
}
void mianji(double a,double b=1.0,double c=1.0)
{
m=a;
n=b;
w=c;
double p=(m+n+w)/2;
double t=sqrt(p*(p-m)*(p-n)*(p-w));
cout<<"三角形的面积是:"<<t<<endl;
}
double m,n,w;
};
class juxing:public tuxing
{
public:
void tuxing1()
{
cout<<"图形是矩形"<<endl;
}
void mianji(double a,double b=1.0,double c=1.0)
{
m1=a;
n1=b;
w1=c;
double t1=m1*n1;
cout<<"矩形的面积是:"<<t1<<endl;
}
double m1,n1,w1;
};
class zheng:public tuxing
{
public:
void tuxing1()
{
cout<<"图形是正方形"<<endl;
}
void mianji(double a,double b=1.0,double c=1.0)
{
m2=a;
n2=b;
w2=c;
double t2=m2*m2;
cout<<"正方形的面积是:"<<t2<<endl;
}
double m2,n2,w2;
};
class circle:public tuxing
{
public:
void tuxing1()
{
cout<<"图形是圆形"<<endl;
}
void mianji(double a,double b=1.0,double c=1.0)
{
m3=a;
double t3=pi*m3*m3;
cout<<"圆形的面积是:"<<t3<<endl;
}
double m3;
};
int main()
{
sanjiao s;
s.tuxing1();
s.mianji(3.0,4.0,5.0);
juxing j;
j.tuxing1();
j.mianji(3,6);
zheng z;
z.tuxing1();
z.mianji(5);
circle c;
c.tuxing1();
c.mianji(2);
return 0;
}
结果如下:
2.定义一个复数类,通过重载运算符: *,/,直接实现二个复数之间的乘除运 算。编写一个完整的程序,测试重载运算符的正确性。要求乘法“*”用友元函数实现重载,除法“/”用成员函数实现重载。
#include<iostream>
using namespace std;
class complex
{
private:
double real,image;//不能用int型,精度不足
public:
complex(double a,double b)
{
real=a; //实部
image=b; //虚部
}
//complex operator *(const complex & m)const;
friend complex operator *(const complex & t,const complex & m);//友元函数
complex operator /(const complex & n)const;
void display()
{
cout<<real<<"+"<<image<<"i"<<endl;
}
};
//因为友元函数不是成员函数,所以参数要两个类
complex operator *(const complex &t,const complex & m)//这里不能用const,因为不是成员函数
{
double real1=t.real*m.real-t.image*m.image ;
double image1=t.real*m.image +t.image*m.real ;
return complex(real1,image1);
}
complex complex::operator /(const complex & n)const//复数除法
{
double p=n.image*n.image +n.real *n.real ;
double real2=(real*n.real+image*n.image)/p;
double image2=(image*n.real-real*n.image)/p;
return complex(real2,image2);
}
int main()
{
complex c1(1,2);
complex c2(3,4);
complex c3=c1*c2;
c3.display();
complex c4=c1/c2;
c4.display();
return 0;
}
结果如下: