当前位置:编程学习 > C/C++ >>

C++中派生类来求面积

写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。
答案:
#include <stdio.h>
#include <stdlib.h>

#include <iostream>

using namespace std;

const double pi = 3.1415926;

class Shape
{
public:
Shape()
{
}
virtual ~Shape()
{
}
virtual void printArea() = 0;
};

class Circle : public Shape
{
public:
Circle(double radiu)
{
this->radiu = radiu;
}
void printArea()
{
printf("面积是: %f\n", pi * radiu * radiu);
}
private:
double radiu;
};

class Rectangle : public Shape
{
public:
Rectangle(double width, double height)
{
this->width = width;
this->height = height;
}
void printArea()
{
printf("面积是: %f\n", width * height);
}
private:
double width;
double height;
};

class Triangle : public Shape
{
public:
Triangle(double bottom, double height)
{
this->bottom = bottom;
this->height = height;
}
void printArea()
{
printf("面积是: %f\n", bottom * height/2);
}
private:
double bottom;
double height;
};

int main(int argc, char *argv[])
{
Circle c((double)2);
c.printArea();

Rectangle r((double)1, (double)2);
r.printArea();

Triangle t((double)1, (double)2);
t.printArea();

return 0;
}
 class Shape
{
public:
Shape(void);
~Shape(void);
virtual void printArea() = 0;
};

class Circle:Shape
{
public:
Circle(double radiu) {this->radiu = radiu;}
void printArea()
{
printf("面积是: %f", radiu);
}
private:
double radiu;
};

class Rectangle:Shape
{
public:
Rectangle(double width, double height)
{
this->width = width;
this->height = height;
}
void printArea()
{
printf("面积是: %f", width * height);
}
private:
double width;
double height;
};

class Triangle:Shape
{
public:
Triangle(double bottom, double height)
{
this->bottom = bottom;
this->height = height;
}
void printArea()
{
printf("面积是: %f", bottom * height/2);
}
private:
double bottom;
double height;
};

上一个:C和C++语言有什么区别?
下一个:帮忙写一篇简单的c++程序

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,