注册 登录
编程论坛 C++教室

继承与派生的程序编译没错误,运行出错,求解

子楠 发布于 2013-04-09 17:05, 429 次点击
#include<iostream>
using namespace std;
const double PI=3.14159;
class Point
{
    protected:
        double x,y;
    public:
        Point(double xv,double yv){ x=xv; y=yv;}
        double Area(){ return 0;}
        void show()
        {
            cout<<"x="<<x<<' '<<"y="<<y<<endl;
        }
};

class Circle:public Point
{
        double radius;
    public:
        Circle(double xv,double yv,double vv):Point(xv,yv)
        {
            radius=vv;
        }
        Circle(Circle &Cir):Point(Cir)
        {
            radius=Cir.radius;
        }
        double Getradius(){    return radius;}
        double Area(){    return PI*radius*radius;}
        void show()
        {
            cout<<"x="<<x<<' '<<"y="<<y<<' '<<"radius="<<radius<<endl;
        }
};

class Cylinder:public Circle
{
    private:
        double h;
    public:
        Cylinder(double xv,double yv,double vv,double xx):Circle(xv,yv,vv)
        {
            h=xx;
        }
        double Area() { return (2*Area()+2*PI*Getradius()*h); }
        Cylinder(Cylinder &p):Circle(p) { h=p.h; }
        void show()
        {
            cout<<"x="<<x<<' '<<"y="<<y<<' '<<"radius="<<Getradius()<<' '<<"h="<<h<<endl;
        }
};

void main()
{
    Point p(1,2);
    cout<<"点的面积="<<p.Area()<<endl;
    p.show();
    Circle c1(1,2,3),c2(c1);
    cout<<"圆的面积="<<c2.Area()<<endl;
    c2.show();
    Cylinder c3(1,2,3,2),c4(c3);
    cout<<"圆柱的面积="<<c4.Area()<<endl;
    c4.show();
}
运行截图:
只有本站会员才能查看附件,请 登录


[ 本帖最后由 子楠 于 2013-4-9 17:28 编辑 ]
5 回复
#2
fanpengpeng2013-04-09 17:19
     void show()
        {
            cout<<"x="<<x<<' '<<"y="<<y<<' '<<"radius="<<radius<<endl;
        }

基类的私有成员 在派生类中只能通过基类接口访问 不能直接访问
派生类能直接访问的基类成员 只有public和protected成员
#3
子楠2013-04-09 17:24
回复 2楼 fanpengpeng
x,y是保护的,radius是自己的可以调用啊,那里没有错误,就是派生出的圆柱类那里出问题了
#4
fanpengpeng2013-04-09 17:36
class Cylinder:public Circle
{
    private:
        double h;
    public:
        Cylinder(double xv,double yv,double vv,double xx):Circle(xv,yv,vv)
        {
            h=xx;
        }
        double Area() { return ([color=#0000FF]2*Area()+2*PI*Getradius()*h); }[/color]
        Cylinder(Cylinder &p):Circle(p) { h=p.h; }
        void show()
        {
            cout<<"x="<<x<<' '<<"y="<<y<<' '<<"radius="<<Getradius()<<' '<<"h="<<h<<endl;
        }
};

这里Area()的不小心调用构成了无穷递归了 按你的意思 要调用Circle类的这个方法
所以这样改一下
double Area() { return (2*Circle::Area()+2*PI*Getradius()*h); }
#5
fanpengpeng2013-04-09 17:37
不好意思啊 看的太着急了 没仔细看
#6
子楠2013-04-09 17:52
回复 5楼 fanpengpeng
奥,没事。。恩恩,对了,非常感谢
1