demo_inheritance_2_a.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 45 行

CPP
45
字号

//***************************************************
// 私有继承类
//***************************************************

#include<iostream.h>
#include<math.h>

class Point //基类声明
{
public:
	void InitP(float xx=0, float yy=0) {X=xx;Y=yy;}
	void Move(float xOff, float yOff) {X+=xOff;Y+=yOff;}
	float GetX() {return X;}
	float GetY() {return Y;}
private:
	float X,Y;
};
class Rectangle: private Point //派生类声明
{
public: //新增外部接口
	void InitR(float x, float y, float w, float h)
	{ InitP(x,y); W=w; H=h; } //派生类访问基类公有成员
	void Move(float xOff, float yOff) {Point::Move(xOff,yOff);}
	float GetX() {return Point::GetX();}
	float GetY() {return Point::GetY();}
	float GetH() {return H;}
	float GetW() {return W;}
private: //新增私有数据
	float W,H;
};

void main()
{
	Rectangle rect; //定义Rectangle类的对象

	rect.InitR(2,3,20,10); //设置矩形的数据
	rect.Move(3,2); //移动矩形位置

	cout<<"The data of rect(X,Y,W,H):"<<endl;
	cout<<rect.GetX()<<"," //输出矩形的特征参数
		<<rect.GetY()<<","
		<<rect.GetW()<<","
		<<rect.GetH()<<endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?