1. 多态
要求
动态多态性
- 题目描述
- 定义一个抽象类shape,用于代表几何图形,设置计算几何图形体积的外部接口;
- 由shape类派生出圆柱类cylinder、球sphere;圆柱体类型有私有数据成员半径r,高h;球类有私有数据成员半径r;
- 结合抽象类的指针或引用,实现就算几何图形体积。纯虚函数定义:double volume()=0;
- main()已给出,请直接复制使用
int main() {shape *p;double r,h;cout<<"input r & h:"<<endl;cin>>r>>h;cylinder cy(r,h);sphere sp(r);p=&cy;cout<<p-> volume()<<endl; p=&sp;cout<<p-> volume()<<endl; return 0;
}
解答
#include<iostream>
#include<string>
using namespace std;
class shape
{// 抽象类,说明是纯虚
public:virtual double volume()=0;
};
//派生
class cylinder :public shape
{
private:double r;double h;
public:cylinder(double radius, double height) {r = radius;h = height;}virtual double volume() {return 3.1415926 * r * r * h;}
};
class sphere:public shape
{
private:double r;
public:sphere(double radius) :r(radius) {};virtual double volume() {return 3.1415926 * r * r * r * 4.0/3.0;}
};
int main() {shape* p;double r, h;cout << "input r & h:" << endl;cin >> r >> h;//由shape类派生的cylinder cy(r, h);// 圆柱类sphere sp(r);// 球p = &cy;cout << p->volume() << endl;p = &sp;cout << p->volume() << endl;return 0;
}
2. 类
要求
- 题目内容:
设计一个Car类,它的数据成员要能描述一辆汽车的品牌,型号,出厂年份和价格,成员函数包括提供合适的途径来访问数据成员,在main()函数中定义类的对象并调用相应成员函数。
- 设计私有数据成员:
string brand; 或者char *brand;
string type; 或者char *type;
int year;
double price;
- 公有成员函数:
构造函数 :默认品牌undefinition,默认型号undefinition,默认年份2000,默认价格 0;
-
获取数据成员的函数:
-
使用如下的main()函数:
int main() { Car car1("FIAT","Palio",2021,6.5); cout<<car1.GetBrand()<<" "<<car1.GetType()<<" "<<car1.GetYear() <<" " <<car1.GetPrice()<<endl; Car car2; cout<<car2.GetBrand()<<" "<<car2.GetType()<<" "<<car2.GetYear()<<" " <<car2.GetPrice()<<endl; return 0; }
解答
#include<iostream>
#include<string>
using namespace std;
class Car {
private:string brand;string type;int year;double price;
public:Car(string b="undefinition", string t = "undefinition", int y=2000, double p=0.0) :brand(b), type(t), year(y), price(p) {};string GetBrand();string GetType();int GetYear();double GetPrice();};
string Car::GetBrand() {return brand;
}
string Car::GetType() {return type;
}
int Car::GetYear() {return year;
}
double Car::GetPrice() {return price;
}
int main(){Car car1("FIAT", "Palio", 2021, 6.5);cout << car1.GetBrand() << " " << car1.GetType() << " " << car1.GetYear() << " " << car1.GetPrice() << endl;Car car2;cout << car2.GetBrand() << " " << car2.GetType() << " " << car2.GetYear() << " " << car2.GetPrice() << endl;return 0;}