把这个代码改为从键盘输入值 得出结果怎么改啊?
发布网友
发布时间:2023-06-15 01:27
我来回答
共1个回答
热心网友
时间:2024-12-15 03:04
输入对应的变量 然后用变量做构造参数就可以了
大致如下:
#include <iostream.h>
double PI=3.14;
class circle //圆类(基类)
{
public:
circle(double r)
{
radius = r;
}
virtual double area() //虚函数
{
return 0.0;
}
virtual double volume() //虚函数
{
return 0.0;
}
protected:
double radius;
};
class sphere:public circle //派生出球类
{ public:
sphere( double r ):circle( r ){ }
double area()
{
return 4.0 * PI * radius * radius;
}
double volume()
{
return 4.0 /3.0* PI * radius * radius * radius;
}
};
class column:public circle //派生出圆柱类
{
public:
column( double r,double h ):circle( r )
{
height = h;
}
double area()
{
return 2.0 * PI * radius * ( height + radius);
}
double volume()
{
return PI * radius * radius * height;
}
private:
double height;
};
void main()
{
circle *p;
int r, h;
cout << "input r:";
cin >> r;
sphere sobj(r);
p= &sobj;
cout << "球体:" << endl;
cout << "体积 = " << p->volume() << endl;
cout << "表面积 = " << p->area() << endl;
cout << "input r h:";
cin >> r >> h;
column cobj( r,h);
p= &cobj;
cout << "圆柱体:" << endl;
cout << "体积 = " << p->volume() << endl;
cout << "表面积 = " << p->area() << endl;
}
如果要动态修改 则需要写修改对应成员变量的成员函数