《继承方式》

#include<iostream>
using namespace std;
class CAllComers
{
public:
	string m_name;
	string m_tel;
protected :
	int m_a;
private:
	int m_b;
public:
	//构造函数。
	CAllComers(){
		m_name="某女";
		m_tel = "不详" ;
	}
	//报名时需要唱一首歌
	void sing(){
		cout<<"我是一只小小鸟。\n";
	} 
	//设置姓名
	void setname(const string&name){m_name=name;}
	//设置电话号码。
	void settel(const string&tel){m_tel=tel;}
};
class CGirl:private CAllComers
{
public:
	int m_bh;//编号;
	CGirl(){
		m_bh=9;
	} 
	void show(){
		setname("钟哥"); 
		cout<<"编号:"<<m_bh<<",姓名:"<<m_name<<",联系电话:"<<m_tel<<endl; 
	}
	
};
int main(){
	CGirl g;
	//g.setname("钟哥");main函数不可以用g.setname因为CGirl中的setname继承过来是私有的了 ;
	//而CGirl的成员函数是可以访问它自己的私有成员。 
	g.show();
	return 0;
} 

 演示最后一个;

细节:

1.在派生类中可以通过基类的公有成员函数间接访问基类的私有成员。

#include<iostream>
using namespace std;
class A{
private:
	int m_a=10;
public:
	int m_b=20;
};
class B:public A{
	
}; 
int main(){
	B b;
	b.m_a=11;
	return 0;
} 

报错:B继承A,A的private访问不了。

#include<iostream>
using namespace std;
class A{
private:
	int m_a=10;
public:
	int m_b=20;
	func(){
		m_a=11;
		cout<<"m_a="<<m_a<<endl;
	} 
};
class B:public A{
	
}; 
int main(){
	B b;
	b.func();
	return 0;
} 

通过基类的公有成员函数间接访问基类的私有成员。

2.使用using关键字可以改变基类成员在派生类中的访问权限。

但只能改public和protected的,private改不了。

#include<iostream>
using namespace std;
class A{
public:
	int m_a=10;
protected:
	int m_b=20;
private:
    int m_c=30; 
};
class B:public A{
	
}; 
int main(){
	B b;
	b.m_a=11;
	b.m_b=21;
	b.m_c=21;
	return 0;
} 

 报错:m_b m_c 访问不了;

#include<iostream>
using namespace std;
class A{
public:
	int m_a=10;
protected:
	int m_b=20;
private:
    int m_c=30; 
};
class B:public A
{
public:
	using A::m_b;//把m_b的权限改为公有的; 
private:
	using A::m_a;//把m_a的权限改为私有的; 
}; 
int main(){
	B b;
//	b.m_a=11;
	b.m_b=21;
//	b.m_c=21;
	return 0;
} 

现在就剩m_b可以访问。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值