2020-06-09 16:31

# 派生与继承的虚函数问题，有大佬帮忙看看吗

（点类可以直接return 0）

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

#### 1条回答

• qtchen_1988 10月前
``````#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>

using namespace std;
class Point{
public:
Point(){mArea = 0.0;}
virtual double area(){return mArea;}
protected:
double mArea;
};
class Circle:public Point{
public:
Circle(double r){
mArea = M_PI*r*r;
}
};
class Cylinder:public Circle{
public:
Cylinder(double r,double h):Circle(r){
mArea = (M_PI*r*r + M_PI*r*h)*2.0;
}
};

int main()
{
Point *point = new Point;
std::cout << point->area() << std::endl;

Point *circle = new Circle(3.5);
std::cout << circle->area() << std::endl;

Point *cylinder = new Cylinder(3.5,10);
std::cout << cylinder->area() << std::endl;

return 0;
}
``````

///////////////////////////////////////////
//////////////////////////////////////////

``````#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>

using namespace std;
class Point{
public:
Point():mR(0.0){}
virtual double area(){return 0.0;}
protected:
double mR;
};
class Circle:public Point{
public:
Circle(double r){ mR = r;}
virtual double area(){return M_PI*mR*mR;}
};
class Cylinder:public Circle{
public:
Cylinder(double r,double h):Circle(r),mH(h){
}
virtual double area(){return (M_PI*mR*mR + M_PI*mR*mH)*2.0;}
protected:
int mH;
};

int main()
{
Point *point = new Point;
std::cout << point->area() << std::endl;

Point *circle = new Circle(3.5);
std::cout << circle->area() << std::endl;

Point *cylinder = new Cylinder(3.5,10);
std::cout << cylinder->area() << std::endl;

return 0;
}

``````
点赞 评论 复制链接分享