| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 4367 人关注过本帖, 1 人收藏
标题:c++学习笔记
只看楼主 加入收藏
ehszt
Rank: 12Rank: 12Rank: 12
等 级:贵宾
威 望:40
帖 子:1745
专家分:3216
注 册:2015-12-2
收藏
得分:0 
写了一个简单的类继承程序
#include <iostream>
#define PI 3.14159
using namespace std;

class point
{
    private: int a;
             int b;
    public:
        point(int m,int n):a(m),b(n){
        };
        show(){
            cout<<"该圆柱的底面圆心坐标是:"<<"\nX="<<
            a<<"  Y="<<b<<endl;
        }
};
class circle:public point
{
    int r;
    public:
        circle(int m,int n,int a):point(m,n){r=a;}
    double getsquare(){return PI*r*r;}
    virtual void display(){cout<<"圆柱底面面积为:"<<PI*r*r<<endl; //如果取消此处的virtual关键字,bk->display();ck->display();打印的都是底面积
    }
};
class yuanzhu:public circle
{
    int H;
    public:
        yuanzhu(int m,int n,int a,int b):circle(m,n,a){
            H=b;
        }
    double    getvolume(){
        return getsquare()*H;
        }
    virtual    void display(){
            cout<<"圆柱的体积为:"<<getvolume()<<endl;
        }
};
main()
{
    yuanzhu ak(2,3,1,10);
    circle m(2,3,1);
    ak.display();
    ak.circle::display();
    ak.show();
    circle *bk=&ak;
    circle *ck=&m;
    bk->display();
    ck->display();
   
}

[此贴子已经被作者于2018-11-11 12:46编辑过]

2018-11-08 22:15
ehszt
Rank: 12Rank: 12Rank: 12
等 级:贵宾
威 望:40
帖 子:1745
专家分:3216
注 册:2015-12-2
收藏
得分:0 
书上例题:
class shape{
    public:
        virtual double area()=0;
};

class square:public shape{
    protected:
        double H;
    public:
        square(double i){H=i;}
        double area(){return H*H;
        }        
};

class circle:public square{
    public:
        circle(double r):square(r){
        }
        double area(){return H*H*3.14159;
        }
};

class triangle:public square{
    protected:
        double W;
    public: triangle(double h,double w):square(h){W=w;
    }
            double area(){return H*W*0.5;
            }
};

class rectangle:public triangle{
    public:
        rectangle(double h,double w):triangle(h,w){
        }
        double area(){return H*W;
        }
};

double total(shape *s[],int n)
{
    double sum=0.0;
    for(int i=0;i<n;i++)
    {
        sum+=s[i]->area();
    }
    return sum;
}

#include <iostream>
using namespace std;
 main()
{
    shape *s[5];
    s[0]=new square(4);        s[1]=new triangle(3,6);
    s[2]=new rectangle(3,6);    s[3]=new square(6);
    s[4]=new circle(10);
    for(int i=0;i<5;i++)
    {
        cout<<"s["<<i<<"]="<<s[i]->area()<<endl;
    }
    double sum=total(s,5);
    cout<<"The total area is:"<<sum<<endl;
}
2018-11-11 13:05
快速回复:c++学习笔记
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.029805 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved