纯虚函数的应用_C++
//
题目描述
Shape是一个父类,他的子类有:
三角形类:Triangle
矩形类:Rectangle
圆形类:Circle
要求如下:
第一:Shape 类中定义纯虚函数 show 和 area;
第二:area 用途:求解图形面积。
show 用途:打印信息。
第三:要求根据输出完善 核心代码实现,要求实现运行时多态。
第四:main() 函数已经给出,需要写出剩余部分的实现。
int main()
{
Shape *s;
Circle mycircle(20);
Rectangle myrect(3,4);
Triangle mytriangle(6,8,10);
s=&mytriangle;//动态多态
s->show();
cout<<"Triangle:"<<s->area()<<endl;
s=&myrect;//动态多态
s->show();
cout<<"Rectangle Area:"<<s->area()<<endl;
mycircle.show();//静态多态
cout<<"Circle Area:"<<mycircle.area()<<endl;
return 0;
}
输入
无
输出
a=6, b=8, c=10
Triangle:24
length=3, width=4
Rectangle Area:12
radius=20
Circle Area:1256.64
样例输入 Copy
无
样例输出 Copy
a=6, b=8, c=10
Triangle:24
length=3, width=4
Rectangle Area:12
radius=20
Circle Area:1256.64
#include<iostream>
#include<string>
using namespace std;
class Shape {
public:
virtual void show() = 0;
virtual int area() = 0;
};
class Triangle:public Shape{
public:
Triangle(int a, int b, int c) {
b1 = a;
b2 = b;
b3 = c;
}
void show() {
cout << "a=" << b1 << ", b=" << b2 << ", c=" << b3 << endl;
}
int area() {
return (b1 * b2) / 2;
}
int b1, b2, b3;
};
class Rectangle :public Shape {
public:
Rectangle(int a, int b) {
b1 = a;
b2 = b;
}
void show() {
cout << "length=" << b1 << ", width=" << b2 << endl;
}
int area() {
return (b1 * b2);
}
int b1, b2;
};
class Circle{
public:
Circle(int a) {
b1 = a;
}
void show() {
cout << "radius=" << b1 << endl;
}
double area() {
return b1 * b1 * 3.14159;
}
int b1;
};
|