0

继承程序class polygon是基类,我创建了一个派生类调用矩形。在我的多边形基类中,我有一个构造函数和析构print函数以及面积和周长的两个函数。在我的派生类中,我有一个构造函数和析构print函数,以及面积和周长的两个函数calc areacalc 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");
}
4

2 回答 2

2

printarea()只是返回成员变量的值area。您a)没有将其初始化为任何东西,并且b)没有计算任何地方的面积。

我会冒险猜测您的输出是零还是垃圾 - 取决于编译器选项 - 因为 area 没有初始化(即给定一个值)。

如果您calcarea()在矩形的构造函数内部调用,或者在实例化它的实例后在 main 中调用,那么printarea()将产生正确的值。您甚至可以calcarea()在内部调用printarea()以确保该值在需要时始终是最新的。

于 2012-12-18T04:04:17.477 回答
0

试试下面的解决方案。这将解决您的问题。

这是我所做的更改:
我已将 Polygon 作为抽象类,因为您只想调用printareaprintperimeterof Polygon。此外,我分别调用了calcareacalcperimeterprintarea尽管在 of / printperimeterof的主体中也可以这样做Rectangle。无需调用calcareaand calcperimeter

#include<iostream>

using namespace std;

class polygon 
{

protected:
    double area;
    double perimeter;
public:
    polygon(){}
    virtual ~polygon(){ }
    virtual double printarea() = 0; 
    virtual double printperimeter() = 0;
};

class rectangle : public polygon
{

public:
    rectangle(double , double ) ;
    ~rectangle(){ }
    double calcarea() ;
    double calcperimeter() ;
    double printarea()  { return calcarea();} 
    double printperimeter() { return calcperimeter() ;}

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");
}
于 2012-12-18T05:03:20.130 回答