编写以下代码#include <iostream> #include <iomanip> #include <cmath> using namespace std; class area_c1{ protected: double height; double width; public: area_c1(double r, double s){ height = r; width = s; } //定义纯虚函数area/使得类area_c1成为抽象类 @-@ }; //定义类rectangle,构造函数和成员函数area //area=height * width @-@ //定义类isosceles,构造函数和成员函数area //area=(height * width)/2 @-@ int main(){ double r1,s1; double r2,s2; cin>>r1>>s1; rectangle r(r1, s1); cin>>r2>>s2; isosceles i(r2, s2); //定义指针基类a @-@ a = &r; cout<< "The area of rectangle:" <<fixed<<setprecision(4)<< a->area() << endl; a = &i; cout << "The area of isosceles:" <<fixed<<setprecision(4)<< a->area() <<endl; return 0; }
时间: 2023-12-06 16:43:28 浏览: 72
这段代码存在问题,因为在类area_c1中定义了纯虚函数area,使得类area_c1成为抽象类,但是没有定义子类rectangle和isosceles中的area函数,导致编译会报错。
另外,在main函数中定义指针a时,需要先定义a的类型,即指向哪个类的指针,否则也会报错。
以下是修改后的代码:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
class area_c1{
protected:
double height;
double width;
public:
area_c1(double r, double s){
height = r;
width = s;
}
virtual double area()=0; //定义纯虚函数area/使得类area_c1成为抽象类
};
class rectangle: public area_c1{ //定义类rectangle,构造函数和成员函数area
public:
rectangle(double r, double s): area_c1(r, s){}
double area(){
return height * width;
}
};
class isosceles: public area_c1{ //定义类isosceles,构造函数和成员函数area
public:
isosceles(double r, double s): area_c1(r, s){}
double area(){
return (height * width) / 2;
}
};
int main(){
double r1,s1;
double r2,s2;
area_c1 *a; //定义指针基类a
cin>>r1>>s1;
rectangle r(r1, s1);
cin>>r2>>s2;
isosceles i(r2, s2);
a = &r;
cout<< "The area of rectangle:" <<fixed<<setprecision(4)<< a->area() << endl;
a = &i;
cout << "The area of isosceles:" <<fixed<<setprecision(4)<< a->area() <<endl;
return 0;
}
阅读全文