private:
inta;
};
classB:
publicA
{
public:
B(inti,intj):
A(i){b=j;cout<<"ConstructorB."<~B(){cout<<"DestructorB."<voidPrint(){A:
:
Print();cout<
private:
intb;
};
classC:
publicB
{
public:
C(inti,intj,intk):
B(i,j),c(k)
{cout<<"ConstructorC."<~C(){cout<<"DestructorC."<voidPrint(){A:
:
Print();B:
:
Print();cout<private:
intc;
};
voidmain()
{
Cc1(1,2,3);
c1.Print();
}
6、分析下列程序,写出运行结果
#include
classTest{
public:
Test(doublem,doublen,doubled):
p(d){x=m;y=n;}
voidShow();
voidShow()const;
private:
doublex,y;
constdoublep;
};
voidTest:
:
Show(){
cout<cout<<"p="<
}
voidTest:
:
Show()const{
cout<cout<<"p="<
}
voidmain(){
Testa(8.9,2.5,3.1416);
a.Show();
constTestb(2.5,8.9,3.14);
b.Show();
}
7、分析下列程序,写出运行结果
#include
classSample
{
intx,y;
public:
Sample(){x=y=0;}
Sample(inta,intb){x=a;y=b;}
~Sample()
{
if(x==y)
cout<<"x=y"<else
cout<<"x!
=y"<}
voiddisp()
{
cout<<"x="<}
};
voidmain()
{
Samples1,s2(2,3);
s1.disp();
s2.disp();
}
8、分析下列程序,写出运行结果
#include
classPoint
{
public:
Point(doublem,doublen);
virtualvoidArea();
private:
doublex,y;
};
Point:
:
Point(doublem,doublen)
{x=m;
y=n;
}
voidPoint:
:
Area()
{cout<<”Theareais0”<classCircle:
publicPoint
{
public:
Circle(doublem,doublen,doublei);//声明构造函数
voidArea();
private:
doubler;
};
Circle:
:
Circle(doublem,doublen,doublei):
Point(m,n)
{r=i;}
voidCircle:
:
Area()
{doublea=3.14*r*r;
cout<<”Theareaofthecircleis:
”<}
voidmain()
{Point*pt;
Circlec(4,5,6);
pt=&c;
pt->Area();
}
四、编写程序
1、已知数列:
编一程序,求其前十项的和。
(画出N~S流程图)
#include
usingnamespacestd;
intmain()
{
doublesum,m,n;
inti;
sum=1;
m=1;
n=1;
for(i=1;i<=9;i++)
{
n=n+2;
if(i%2!
=0)
m=-(1/n);
elsem=1/n;
sum+=m;
}
cout<<"前十项的和为:
"<return0;
}
2、编写一函数计算n!
,调用该函数计算sinx的近似值,要求误差小于
,其中:
#include
#include
usingnamespacestd;
intjiecheng(intn)
{
intsum=1,i;
for(i=1;i<=n;i++)
{
sum=sum*i;
}
returnsum;
}
doublemain()
{
doublesinx=0,x;
intn,i;
cout<<"请输入x:
";
cin>>x;
cout<<"请输入n:
";
cin>>n;
for(i=1;i<=n;i++)
{
sinx=pow((-1),(i-1))*pow(x,(2i-1))/jiecheng(2i-1);
}
cout<<"sinx=";
printf("%10.4\n",sinx);
return0;
}
3、定义一复数类,利用运算符重载完成复数相加。
主函数及运行结果如下:
(注意:
实部为real;虚部为imag,为私有数据成员)
#include
classComplex
{public:
Complex()
{
real=0;
Image=0;
}
Complex(doubler,doublei):
real(r),imag(i){}
Complexoperator+(Complexb&c2);
{
return(real+c2.real,imag+c2.imag)
}
Voidput()
{
cout<<”(“<}
private:
doubleraeal;
doubleimage;
};
voidmain()
{Complexc1(1,2),c2(3,4),c3;
c3=c1+c2;
c3.put();
}
4、编写一函数把字串中与某字符相同的字符删除,主函数如下:
#include
#include
main()
{
char*str=newchar[];
charc;
gets(str);
cin>>c;
fun(str,c);
puts(str);
}
voidfun(str,c)
{
while(str[]!
=’\0’)
{
if(strcmp(str[],c)==0)
deletestr[];
}
}
5、已知三角形的三遍,在该三角形的基础上拉伸出高为H的三棱柱,编写三棱柱派生类,求三棱柱的体积。
三角形类描述如下:
cl