C++学习笔记43——protected访问标识符

本文详细解释了C++中protected成员的作用及访问规则,并通过具体示例展示了派生类如何访问基类的protected成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,访问标识符汇总



定义在protected标号之后的成员可以被类成员(成员函数)、友元、和派生类成员访问。类的普通用户不能访问protected成员。

2,继承与保护

难点在于这一句话:
派生类只能通过派生类对象访问基类的protected成员,派生类对其基类类型对象的protected成员没有特殊访问权限。

自己的理解:
1,假设基类father中有一个protected成员叫test,不管是数据成员还是函数成员,由于继承,其派生类son获得了一个一样的protected成员test;
2,一个类,只有在其成员函数的定义体中才能使用自己的protected成员,用户代码中无法使用;
3,所以,在基类father的成员函数定义中可以使用基类的protected成员;
4,同样,在派生类son的成员函数定义体中可以使用son的protected成员,这个成员可能是继承自father类的;
5,但是,在派生类son的成员函数定义体中不能通过引入一个father类的对象来使用father类的protected成员;

例子如下:
/*******************************************************************/
//   protected
/*******************************************************************/
class apple
{
public:
	apple(string col, double wei) :color(col), weight(wei) {};
public :
	string color;
protected:
	double weight;
};

class Father
{
protected:
	void test() { printf("Father:test()\n"); }
};

class Son : public Father
{
public:
	void bTest() 
	{ 
		//用的是从父类继承而来的,自己的protected成员
		test(); //protected成员在此处可用 this->test();
	} 

	//错误的成员函数定义
	//void bTest_new(Father& f)
	//{
	//	//用的是父类的protected成员		
	//	f.test(); ////error C2248: “Father::test”: 无法访问 protected 成员(在“Father”类中声明)
	//}
};

//main
int main()
{
	//1, 在用户代码中不可见
	apple fushi("red", 50);
	cout << fushi.color << endl;
	//cout << fushi.weight << endl;// error C2248 : “apple::weight” : 无法访问 protected 成员(在“apple”类中声明)

	//2, 在子类的成员函数中
	Father f;
	Son s;
	//f.test(); //error C2248: “Father::test”: 无法访问 protected 成员(在“Father”类中声明)
	//s.test(); //error C2248: “Father::test”: 无法访问 protected 成员(在“Father”类中声明)
	s.bTest();  //bTest为public
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值