题目1
/****************************************************************
【基本题】定义了一个基类Animal, 它包含两个数据成员动物名称(string类型)和重量,
还包含一个公共的虚拟成员函数who() 和一个纯虚函数sound()。
公共的虚拟成员函数who(),显示名称和重量,在派生类中sound() ,显示示该动物发出的声音。
把Animal类作为一个公共基类,派生三个子类Sheep,Dog和Cow,在每个类中实现sound()函数。
定义一个类Zoo,它至多可以在一个数组中存储50种不同类型的动物(使用指针数组)。
编写一个main()函数,创建给定数量的派生类对象,在Zoo对象中存储这些对象的指针。
使用Zoo对象的一个成员函数,输出Zoo中每个动物的信息,以及每个动物发出的声音。
*************************************************************/
#include <iostream>
#include <string>
using namespace std;
class Animal{
private:
string animal_name;
float weight;
public:
Animal():animal_name("zoo"),weight(120){}
Animal(string a,float w):animal_name(a),weight(w){}
virtual void who(){}
virtual void sound(){}
void GetWho(){
cout<<animal_name<<endl<<weight<<endl;
}
};
class Sheep: public Animal{
public:
Sheep(): Animal(){}
void who();
void sound(){
cout<<"咩"<<endl;
}
};
void Sheep::who(){
GetWho();
}
class Dog: public Animal{
public:
Dog(): Animal(){}
void who();
void sound(){
cout<<"汪"<<endl;
}
};
void Dog::who(){
GetWho();
}
class Cow: public Animal{
public:
Cow(): Animal(){}
void who();
void sound(){
cout<<"哞"<<endl;
}
};
void Cow::who(){
GetWho();
}
class Zoo{
private:
Animal **panimal;
public:
void getsound(Animal *obj[], int num);
};
void Zoo::getsound(Animal *obj[],int num){
panimal=obj;
for(int i=0;i<num;i++){
panimal[i]->sound();
panimal[i]->who();
}
}
题目2
//【基本题】 Shape类是一个表示形状的抽象类,其中GetArea()为求图形面积的纯虚函数。
//从Shape类派生三角形类(Triangle)、矩形类(Rectangle),椭圆类(Ellipse)并重写GetArea()函数完成求面积的功能。
//GetTotalArea(…)则是一个用以求不同形状的图形面积总和的函数,完成该函数。
//写出main函数:创建多个三角形或矩形或椭圆对象(个数不定,由用户的输入指定),
//并调用GetTotalArea()函数求出它们的总面积。
//提示:
//1. GetTotalArea()应设计成全局函数
#include <iostream>
#define PI 3.1415926
using namespace std;
class Shape{
public:
virtual float GetArea(){}
friend float GetTotalArea(Shape * obj[],int num);
};
float GetTotalArea(Shape * obj[],int num){
float S=0;
for(int i=0;i<num;i++){
S+=obj[i]->GetArea();
}
cout<<S<<endl;
return S;
}
class Triangle: public Shape{
public:
virtual float GetArea();
Triangle(float b=1.5,float h=2):Bottom(b),High(h){}
private:
float Bottom;
float High;
};
float Triangle::GetArea(){
float S;
S=Bottom*High/2;
cout<<S<<endl;
return S;
}
class Rectangle: public Shape{
public:
float GetArea();
Rectangle(float L=1.5,float W=2):Lenght(L),Width(W){}
private:
float Lenght;
float Width;
};
float Rectangle::GetArea(){
float S;
S=Lenght*Width;
cout<<S<<endl;
return S;
}
class Ellipse: public Shape{
public:
float GetArea();
Ellipse(float a=1.5,float b=2){
this->a=a;
this->b=b;
}
private:
float a; //长半轴
float b; //短半轴
};
float Ellipse::GetArea(){
float S;
S=a*b*PI;
cout<<S<<endl;
return S;
}
网友评论