背景:
私有继承
源代码:
//rectangle.h
class point
{
private:
float X,Y;
public:
void InitP(float xx = 0, float yy = 0)
{
X = xx;
Y = yy;
}
void Move(float xff,float yff)
{
X += xff;
Y += yff;
}
float GetX() {return X;}
float GetY() {return Y;}
};
class rectangle:private point
{
private:
int W,H;
public:
void InitR(float x,float y,float w,float h)
{
InitP(x,y);
W = w;
H = h;
}
void Move(float xff,float yff)
{
point::Move(xff,yff);
}
float GetX() {return X;}
float GetY() {return Y;}
//float GetX() {return point::GetX();} //去掉之后能访问X,Y
//float GetY() {return point::GetY();}
float GetW() {return W;}
float GetH() {return H;}
};
//main()
#include <iostream>
#include "rectangle.h"
using namespace std;
int main()
{
rectangle rect;
rect.InitR(1,2,3,4);
rect.Move(1,2);
cout << rect.GetX() << ","
<< rect.GetY() << ","
<< rect.GetW() << ","
<< rect.GetH() << endl;
return 0;
}
错误提示:
error C2248: 'X' : cannot access private member declared in class 'point'
see declaration of 'X'
error C2248: 'Y' : cannot access private member declared in class 'point'
see declaration of 'Y'
错误分析:
不能在类外用rectangle的对象访问GetX(),GetY(),原因何在?
研究结果(知识扩展):
私有继承后,派生类成员可以访问到从基类继承过来的公有和保护成员,但在类外部通过派生类的对象无法直接访问到基类的任何成员
可以用派生类把基类的外部接口封装起来