c++学习2011-03-02

背景:
私有继承

 

源代码:
//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(),原因何在?

 

研究结果(知识扩展):
私有继承后,派生类成员可以访问到从基类继承过来的公有和保护成员,但在类外部通过派生类的对象无法直接访问到基类的任何成员
可以用派生类把基类的外部接口封装起来

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值