C++学习笔记——私有继承

      当类的继承方式为私有继承时,在派生类中,基类的共有成员和保护成员作为派生类的私有成员。此时有:派生类的成员函数可以直接访问基类的共有成员和保护成员,而无法直接访问基类的私有成员。
      在类外部,派生类的成员无法访问基类的所有成员。
举个栗子:
调用库:
#include<iostream>
using namespace std;
基类:
// 基类
class Point	
{
public:	// 公有成员
	void setxy(int myx, int myy) { X = myx; Y = myy; };	 // 两个外部接口
	void movexy(int x, int y) { X += x; Y += y; };
protected: // 保护成员
	int X, Y;
};
派生类:
// 派生类
class Circlr :private Point
{
public:
	void setr(int myx, int myy, int r) { setxy(myx, myy); R = r; };
	void movexy(int x, int y) { Point::movexy(x, y); };	// 基类中的movexy()接口变为派生类的私有成员,外部无法直接访问,需要增加新的外部接口。
	void display();
private:
	int R;
};
void Circlr::display()
{
	cout << "The position of center is: ";
	cout << "(" << X << " , " << Y << ")" << endl;
	cout << "The radius of circle is " << R << endl;
}
主函数:
int main()
{
	Circlr c;
	c.setr(2, 3, 4);
	cout << "Thre start data of circlr : " << endl;
	c.display();
	c.movexy(7, 8);
	cout << "The new data of Circle : " << endl;
	c.display();
	return 0;
}
运行结果:
Thre start data of circlr :
The position of center is: (2 , 3)
The radius of circle is 4
The new data of Circle :
The position of center is: (9 , 11)
The radius of circle is 4
注意事项:

      在私有继承时,基类的外部接口会被封装成派生类的私有成员!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值