#include <iostream> using namespace std; class Figure { protected: double x,y; public: Figure(double a,double b){ x=a;y=b; } virtual void area( )=0; }; /* 请在这里填写答案 */ int main( ) { Figure *p; //定义指针 Triangle t(10.0,6.0); //定义三角形类对象t Square s(10.0,6.0); //定义矩形类对象s p=&t;p->area(); p=&s;p->area(); return 0; }
时间: 2023-06-16 20:04:13 浏览: 86
代码中需要先定义派生类 Triangle 和 Square,这两个类都继承自 Figure 基类,并重写了 area() 纯虚函数。修改后的代码如下:
#include <iostream>
using namespace std;
class Figure {
protected:
double x,y;
public:
Figure(double a,double b){
x=a;
y=b;
}
virtual void area()=0;
};
class Triangle : public Figure {
public:
Triangle(double a,double b) : Figure(a, b) { }
void area() {
cout << "Triangle area: " << x * y / 2 << endl;
}
};
class Square : public Figure {
public:
Square(double a,double b) : Figure(a, b) { }
void area() {
cout << "Square area: " << x * y << endl;
}
};
int main() {
Figure *p;
Triangle t(10.0,6.0);
Square s(10.0,6.0);
p=&t;p->area();
p=&s;p->area();
return 0;
}
输出结果为:
Triangle area: 30
Square area: 60
阅读全文