C++对象继承和虚函数编程
发布网友
发布时间:2022-05-04 08:02
我来回答
共1个回答
热心网友
时间:2022-06-20 19:00
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
const double PI = 3.14159;
class Shape
{
protected:
string name;
public:
Shape(string n) : name(n){}
string getName(){return name;}
virtual double area() = 0;
virtual double perimeter() = 0;
};
class Rectangle : public Shape
{
protected:
double length;
double width;
public:
Rectangle(string n, double l, double w) : Shape(n), length(l), width(w){}
void setL(double l){length = l;}
double getL(){return length;}
void setW(double w){width = w;}
double getW(){return width;}
double area(){return length * width;}
double perimeter(){return 2 * (length + width);}
};
class Circle : public Shape
{
protected:
double radius;
public:
Circle(string n, double r) : Shape(n), radius(r){}
void setR(double r){radius = r;}
double getR(){return radius;}
double area(){return radius * radius * PI;}
double perimeter(){return 2 * radius * PI;}
};
int main()
{
Shape *p[2];
p[0] = new Rectangle("矩形", 3, 5);
p[1] = new Circle("圆形", 4);
cout << p[0] -> getName() << "的面积是: " << p[0] -> area() << endl;
cout << p[0] -> getName() << "的周长是: " << p[0] -> perimeter() << endl;
cout << p[1] -> getName() << "的面积是: " << p[1] -> area() << endl;
cout << p[1] -> getName() << "的周长是: " << p[1] -> perimeter() << endl;
for(int i = 0; i < 2; i++)
{
delete p[i];
p[i] = NULL;
}
return 0;
}
参考资料:MADE IN 华软