大神帮我看看,我不会用函数啊,而且这提示说的也不懂,既然是全局函数,要派生有什么用?

已知一个全局函数printArea(arg),其中,arg为某一种平面图形,该函数的作用是打印参数arg所表示图形的面积。先假设,只存在正方形、圆形、正三角形三种平面图形。使用继承的方式,设计相关的类,并实现该全局函数的功能。
提示:设计基类Shape,设计派生类Square,Circle,Triangle

4个回答

这是代码有不适当的地方请大家提出来,谢谢
#include
#include
using namespace std;

class Shape
{
public:
virtual double area() = 0;
};

class Circle :public Shape
{
public:
Circle(int radius){
this->radius = radius;
}
virtual double area(){
return 3.14*radius*radius;
}
private:
int radius;
};
class Square :public Shape
{
public:
Square(int rim){
this->rim = rim;
}
virtual double area(){
return rim*rim;
}
private:
int rim;
};

class Triangl :public Shape
{
public:
Triangl(double rim){
this->rim = rim;
}
virtual double area(){
double i = rim*rim;
double j = (rim/2)*(rim/2);
double hige = sqrt(i - j);
return rim*hige/2;
}
private:
double rim;
};

void printArea(Shape *arg)
{
cout << arg->area() << endl;
}

int main(int argc, char* argv[])
{
Shape *squ = new Square(2);
Shape *cir = new Circle(2);
Shape *tri = new Triangl(5);

printArea(squ);
printArea(cir);
printArea(tri);

delete squ;
delete cir;
delete tri;

return 0;

}

s332031515
一行白鹭上青天 思路就是定义一个Shape抽象层和他的纯虚函数,通过各个图形继承Shape,并实现自己的功能,定义一个接口printArea()
3 年多之前 回复

全局函数只是起个调用相关图形的计算面积打印结果的作用,他的参数就是定义为基类类型,运行时再动态判断,使用继承是让你实现 多态的技术,基类可以直接就写个虚方法计算面积,然后子类继承基类实现基类的虚方法就可以了

#include
#include
#define P (3.14)
using namespace std;

class Shape

{
public:
virtual double area() = 0;

double side;
};

class Circle :public Shape
{
public:
Circle(double side){
this->side = side;
}
virtual double area(){

return P*side*side;
}
};
class Square :public Shape

{
public:
Square(double side){
this->side = side;
}
virtual double area(){

return side*side;
}
};

class Triangl :public Shape
{
public:
Triangl(double side){
this->side = side;
}
virtual double area(){

double i = side*side;
double j = (side/2)*(side/2);
double hige = sqrt(i - j);
return side*hige/2;
}
};

void printArea(Shape *arg)
{
cout << arg->area() << endl;
}

int main(int argc, char* argv[])
{
Shape *squ = new Square(2);
Shape *cir = new Circle(2);
Shape *tri = new Triangl(5);

printArea(squ);
printArea(cir);
printArea(tri);

delete squ;
delete cir;
delete tri;

return 0;

}

grapple_Eisen
grapple_Eisen 谢谢你,对我非常有用,我没有系统学习函数的知识,但是现在学到了很多。谢谢你。
3 年多之前 回复

求代码,谢谢了,函数真的是不会。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问