公有继承

本文介绍了一个简单的C++程序,定义了三维空间中的点和球体类,并演示了如何使用这些类来创建对象并展示其属性。点类包含私有、保护和公有成员变量,而球体类作为点类的派生类,增加了半径属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>


using namespace std;
class point{
   float x;
   protected:
       float y;
   public:
    float z;
    point(float x,float y,float z){
    this -> x = x;this -> y =y;this -> z =z;
    }
    void setx(float x){this -> x = x;}
    void sety(float y){this -> y = y;}
    float getx(){return x;}
    float gety(){return y;}
    void showp(){
    cout << '(' << x <<','<< y <<','<< z << ')' ;//在公有继承的派生类中,直接访问基类的保护成员y和公有成员z;但是不能直接访问基类的私有成员x
        }
};
class sphere :public point{
  float radius;
  public:
      sphere(float x,float y,float z,float r):point(x,y,z){
      radius = r;
      }
      void shows(){
      cout << '(' << getx() <<',' << y << ',' << z << ")," << radius << endl;
      }
} ;//公有继承point类,派生类sphere类;


int main()
{
    sphere s(1,2,3,4);
    s.shows();
    cout << '(' << s.getx() <<',' <<s.gety() <<','<< s.z <<")\n";//派生类对象s只能访问类中的公有成员不访问类中的私有成员和保护成员
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值