};
[3]intPoint:
:
count=0;//静态数据成员的初
始化为0
intmain()
{
Point:
:
ShowCount();
Point*p=newPoint;
Point:
:
ShowCount();
deletep;
Point:
:
ShowCount();
return0;
}
4.将如下程序补充完整。
#include
usingnamespacestd;
classComplex
{
private:
doublerealPart;
doubleimagePart;
public:
Complex(doublereal=0,doubleimage=0):
realPart(real),imagePart(image){}
doubleGetRealPart()const{returnrealPart;}
doubleGetImagePart()const{returnimagePart;}
[4]Complexoperator+(constComplex&a)const//重载加法运算
符+
{
Complexb;
b.realPart=this->realPart+a.realPart;
b.imagePart=this->imagePart+a.imagePart;
returnb;
}
};
intmain()
{
Complexa(1,2),b(2,6),c;
c=a+b;
cout<<"a="<cout<<"b="<cout<<"c="<return0;
}
五、编程题(本大题共2小题,第1小题12分,第2小题16分,共28分)
1.编写一个函数模板,用于求参数的绝对值,并编写测试程序进行测试。
函数模板声明如下:
template
TypeAbs(Typea);
1.参考程序:
#include
usingnamespacestd;
template
TypeAbs(Typea)
{
if(a>=0)returna;
elsereturn-a;
}
intmain()
{
cout<cout<cout<cout<return0;
}
2.定义一个复数类Complex,定义带有2个参数(其中一个为缺省参数)的构造函数,显
示复数值的函数Show(),重载“+”运算符(用成员函数实现),并编写测试程序进行测试。
参考程序:
#include
usingnamespacestd;
classComplex
{
public:
Complex(doubler,doublei=0)
{
real=r;
image=i;
}
voidShow()
{
cout<if(image>0)cout<<"+"<elseif(image<0)cout<<"-"<<-image<<"i"<elsecout<}
Complexoperator+(constComplex&obj)
{
Complextemp(real+obj.real,image+obj.image);
returntemp;
}
private:
doublereal,image;
};
intmain()
{
Complexz1(2,6),z2(3,8),z3(0);
z1.Show();
z2.Show();
z3.Show();
z3=z1+z2;
z3.Show();
return0;
}