###### grapple_Eisen

2016-06-05 11:09 阅读 1.3k

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

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享

#### 4条回答默认 最新

• 已采纳
一行白鹭上青天 2016-06-05 12:01

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

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

class Circle :public Shape
{
public:
}
virtual double area(){
}
private:
};
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;
``````

}

点赞 1 评论 复制链接分享
• glustful 2016-06-05 11:52

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

点赞 1 评论 复制链接分享
• 一行白鹭上青天 2016-06-05 12:34

#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;
``````

}

点赞 1 评论 复制链接分享
• grapple_Eisen 2016-06-05 11:10

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

点赞 评论 复制链接分享