C++学习(1)--基类、派生类的对象空间
来源:互联网 发布:双系统ubuntu引导恢复 编辑:程序博客网 时间:2024/05/30 04:16
#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;}