C++ | 实验八 | 虚函数和抽象类

【项目1:形状类族中的纯虚函数】

定义抽象基类Shape,由它派生出3个派生类:Circle(圆形)、Rectangle(矩形)、Triangle(三角形)。在主函数中分别求出一个圆形、一个矩形和一个三角形的面积。

#include <iostream>
using namespace std;
const float PI = 3.14;

class Shape    
{                                     //抽象基类,不用来创建对象,不需要构造函数,必包括纯虚函数
public:
	virtual float area() const { return 0; }
	virtual void shapeName() const = 0; 
};


class Circle :public Shape
{
public:
	Circle(float r1 = 0);
	
	virtual void shapeName() const { cout << "circle: "<<endl; }
	virtual float area() const { return PI * r * r; }
	
protected:
	float r;
};
Circle::Circle(float r1) :r(r1){}

class Rectangle :public Shape
{
public:
	Rectangle(float x1=0, float y1=0);
	virtual void shapeName() const { cout << "Rectangle: "<<endl; }
	virtual float area() const { return x*y; }
	
	
protected:
	float x, y;
};
Rectangle::Rectangle(float x1,float y1):x(x1),y(y1){}

class Triangle :public Shape
{
public:
	Triangle(float x1 = 0, float y1 = 0, float z1 = 0);
	virtual void shapeName() const { cout << "cylinder: " << endl; }
	virtual float area() const {
		double p = (a + b + c) / 2;
		double S = pow(p*(p - a)*(p - b)*(p - c), 0.5);
		if (a + b < c || a + c < b || b + c < a)
			cout << "无法构成三角形!";
		return S;
	}


protected:
	float a, b, c;
};
Triangle::Triangle(float x, float y, float z) :a(x),b(y),c(z) {}

int main()
{
	Circle c1(5);
	Rectangle r1(3, 4);
	Triangle t1(3.0, 4.5, 5.2);

	Shape *p;  //如果指针一开始不是抽象类,无法让指针指向新的类对象
	p = &c1;
	(*p).shapeName();
	cout << "面积为:" << (*p).area() << endl;

	p = &r1;
	(*p).shapeName();
	cout << "面积为:" << (*p).area() << endl;

	p = &t1;
	(*p).shapeName();
	cout << "面积为:" << (*p).area() << endl;

	system("pause");
	return 0;
}
 

 

 

输入

一个小客车的信息(包括车牌号、车轮数、荷载人数)
一个货车的信息(包括车牌号、车轮数、荷载吨数)

输出

该小客车的信息(包括车牌号、车轮数、荷载人数)
该货车的信息(包括车牌号、车轮数、荷载吨数)

样例输入

14235 4 4
3345 6 20

样例输出

车牌号:14235 
车轮数:4
荷载人数:4
车牌号:3345 
车轮数:6
荷载吨数:20
#include <iostream>
#include<string>//如果不加,就无法用cout输出字符串
using namespace std;
class Auto
{
public:
	Auto(string ca, int wh) :card(ca), wheel(wh) {}
	virtual void show() =0;
protected:
	string card;
	int wheel;

};


class Car :public Auto
{
public:
	Car(string ca, int wh, int hn) :Auto(ca, wh), human(hn) {}
	virtual void show() {
		cout << "车牌号:" << card << endl;
		cout << "轮胎数:" << wheel << endl;
		cout << "荷载人数:" << human << endl;
	}
protected:
	int human;
};



class Truck :public Auto
{
public:
	Truck(string ca, int wh, int lo) :Auto(ca, wh), loan(lo) {}
	
	virtual void show() {
		cout << "车牌号:" << card << endl;
		cout << "轮胎数:" << wheel << endl;
		cout << "荷载吨位:" <<loan << endl;
	}

private:
	int loan;
};


int main()
{
	Car c1("晋A0301",4, 5);
	Truck t1("晋A6433", 8, 30);
	Auto *p = &c1;
	(*p).show();
	p = &t1;
	(*p).show();
	system("pause");
	return 0;
}

 

posted @ 2018-12-12 22:05  心碎人俱乐部  阅读(23)  评论(0)    收藏  举报