继承程序class polygon
是基类,我创建了一个派生类调用矩形。在我的多边形基类中,我有一个构造函数和析构print
函数以及面积和周长的两个函数。在我的派生类中,我有一个构造函数和析构print
函数,以及面积和周长的两个函数calc area
和calc perimeter
函数。我不明白的是我现在运行这个程序时得到的输出。我想要的输出是area = 45 perimeter = 28
. 我在使用时得到这个输出,rect_1.calcarea()
但希望它使用rect_1.printarea()
.
#include<iostream>
using namespace std;
class polygon
{
protected:
double area;
double perimeter;
public:
polygon(){}
virtual ~polygon(){ }
virtual double printarea() const { return area ;}
virtual double printperimeter() const { return perimeter ;}
};
class rectangle : public polygon
{
public:
rectangle(double , double ) ;
~rectangle(){ }
double calcarea() ;
double calcperimeter() ;
virtual double printarea() const { return area ;}
virtual double printperimeter() const { return perimeter ;}
private:
double length;
double width;
};
rectangle::rectangle(double l , double w)
{
length = l;
width = w;
}
double rectangle::calcarea()
{
area = length*width;
return area;
}
double rectangle::calcperimeter()
{
perimeter = length + width;
perimeter = perimeter * 2;
return perimeter;
}
void main ()
{
rectangle rect_1 (9.0, 5.0);
cout<<"The Area of Rect_1 is " <<rect_1.printarea() <<endl;
cout<<"The Perimeter of Rect_1 is " <<rect_1.printperimeter() <<endl;
system("pause");
}