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

来源:互联网 发布:淘宝包邮够邮费吗 编辑:程序博客网 时间:2024/05/22 02:23

观察下列程序中产生的两个对象的地址空间及其内容

 

/************************************************************************
* 基类和派生类例子
***********************************************************************
*/


#include 
<IOSTREAM.H>
#include 
<CONIO.H>

//基类
class CMyBase
{
    
int
 x;
public
:
    
int SetX(int nValue){return x=nValue;}

    
int GetX(){return x;}
    
void print(){cout<<"in the base class : x = "<<x<<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;}
}
;

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

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

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

    
return 0
;
}

 


1.基类和派生类的对象的值

 

 

2.基类和派生类的成员函数的地址

3.基类和派生类的对象的地址及其成员变量的地址


原创粉丝点击