C++期末练习

1. 多态

要求

动态多态性

  • 题目描述
  1. 定义一个抽象类shape,用于代表几何图形,设置计算几何图形体积的外部接口;
  2. 由shape类派生出圆柱类cylinder、球sphere;圆柱体类型有私有数据成员半径r,高h;球类有私有数据成员半径r;
  3. 结合抽象类的指针或引用,实现就算几何图形体积。纯虚函数定义:double volume()=0;
  4. 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;

}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值