c++形状区域:获取区域0

C++ Area of Shape: Getting Area 0

本文关键字:区域 获取 c++      更新时间:2023-10-16

下面代码中三角形和矩形的面积为0。需要一些关于如何解决这个问题的建议。此外,如果我能得到一些固定在这个,这将是伟大的!

#include <iostream.h>
#include <conio.h>
class shape
{
protected:
    double x,y;
public:
    void get_data(void);
    virtual void display_area(void){ }
};
class triangle:public shape
{
protected:
    double AoT;
public:
    void display_area(void);
};
class rectangle:public shape
{
protected:
    double AoR;
public:
    void display_area(void);
};
void shape::get_data(void)
{
    cout<<"Enter the vlaue of Base(x) and Height(y):"<<endl;
    cin>>x>>y;
}
void triangle::display_area(void)
{
    AoT=0.5*x*y;
    cout<<"The area of Triangle in unit sq. is:"<<AoT<<endl;
}
void rectangle::display_area(void)
{
    AoR=x*y;
    cout<<"The area of Rectangle in Unit sq. is:"<<AoR<<endl;
}
main()
{
    clrscr();
    shape s, *p;
    triangle t;
    rectangle r;
    s.get_data();
    p=&t;
    p->display_area();
    p=&r;
    p->display_area();
    getch();
}

提前感谢。需要快速解决这个问题,因为我有点失望

str是完全不相关的对象。调用s.get_data()只修改s.xs.y,不能修改t.xt.y,也不能修改r.xr.y。您需要分别为tr调用shape::get_data:

p=&t;
p->get_data();
p->display_area();
p->get_data();
p=&r;
p->display_area();