编写一个程序,声明抽象基类shape,由它派生出3个派生类: circle (圆形)、rectangle(矩形)、triangle (三角形),用一个函数printcircum(const shape
时间: 2023-06-05 09:47:04 浏览: 458
& s)来输出每个派生类的周长。其中,printcircum函数的参数为shape类的引用,因为它可以接受任何派生类的对象作为参数。
程序如下:
```c++
#include <iostream>
using namespace std;
class shape {
public:
virtual double circumference() const = 0; // 纯虚函数
};
class circle : public shape {
private:
double radius;
public:
circle(double r) : radius(r) {}
double circumference() const {
return 2 * 3.14 * radius;
}
};
class rectangle : public shape {
private:
double length, width;
public:
rectangle(double l, double w) : length(l), width(w) {}
double circumference() const {
return 2 * (length + width);
}
};
class triangle : public shape {
private:
double a, b, c;
public:
triangle(double x, double y, double z) : a(x), b(y), c(z) {}
double circumference() const {
return a + b + c;
}
};
void printcircum(const shape& s) {
cout << "周长为:" << s.circumference() << endl;
}
int main() {
circle c(5);
rectangle r(3, 4);
triangle t(3, 4, 5);
printcircum(c);
printcircum(r);
printcircum(t);
return 0;
}
```
运行结果:
```
周长为:31.4
周长为:14
周长为:12
```
阅读全文