C++学习(1)--基类、派生类的对象空间

#include<iostream>
#include<stdio.h>
using namespace std;
//基类
class CMyBase
{
    int x;
    int y;
public:

    int SetX(int nValue){return x=nValue;}
    int GetX(){return x;}
    int SetY(int nValue){return y=nValue;}
    int GetY(){return y;}
    void print(){cout<<"in the base class : x = "<<x<<endl;}
    void printY(){cout<<"in the base class : y = "<<y<<endl;}
};

//派生类
/**公有派生类*/
//基类共有成员相当于派生类的公有成员
//基类私有成员派生类无论如何都不能访问
//基类保护成员相当于派生类的保护成员
/**私有派生*/
//基类共有成员相当于派生类的私有成员
//基类私有成员派生类无论如何都不能访问
//基类保护成员相当于派生类的私有成员
class CMyDerive:public CMyBase
{
    int x;    //派生类中的成员变量隐藏基类的成员变量
public:
    int SetX(int nValue){return x=nValue;}
    int GetX(){return x;}
    //基类中的成员函数被重新定义
    void print(){cout<<"in the derive class : x = "<<x<<endl;}
    void printY(){cout<<"in the derive class : y = "<<GetY()<<endl;}
};

int main()
{
    CMyBase obj1;
    obj1.SetX(1000);
    obj1.print();//1000
    cout<<"in main function, in the base    class : x = "<<obj1.GetX()<<endl;//1000
    cout<<endl;

    CMyDerive obj2;
    obj2.SetX(300);//初始化派生类私有成员x
    obj2.print();//300

    obj2.SetY(123456);
    obj2.printY();//访问派生类私有成员
    obj2.CMyBase::printY();//访问基类公共成员
    /*
    **为了解决二义性,通过在所访问的成员名前加上所属类域来强制访问基类的成员
    **
    */
    obj2.CMyBase::print();//4273296  由于基类中的x没有初始化,所以得到的是个不确定的值
     cout<<"in main function, in the derived class : x = "<<obj2.GetX()<<endl;//300
    cout<<"in main function, in the base    class : x = "<<obj2.CMyBase::GetX()<<endl;//4273296

    obj2.CMyBase::SetX(200);//初始化
    obj2.print();//300
    obj2.CMyBase::print();//200
    cout<<"in main function, in the derived class : x = "<<obj2.GetX()<<endl;//300
    cout<<"in main function, in the base    class : x = "<<obj2.CMyBase::GetX()<<endl;//200

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值