第十二周 任务一

本文通过修改基类成员的访问限定符和派生类的继承方式,探讨了不同继承方式下派生类成员的访问属性变化。总结了公有、保护和私有继承的特点及其对派生类成员访问的影响。
/*【任务1】理解基类中成员的访问限定符和派生类的继承方式
由下面派生类Student1对基类Student的继承……
(1)请修改基类中成员的访问限定符和派生类的继承方式,考虑可能的运行结果或可能出现的错误,并在上机时进行验证、对比,达到理解派生类成员的访问属性的目的。
(2)总结(1)的结果,将(1)的结果摘要写到报告博文中;最后用自己的话总结确定派生类成员的访问属性的原则,也写到报告博文中。
(代码类似P363例11.5,上机准备阶段可以研究这段代码,BB平台中提供实验用代码。)*/
#include<iostream>

#include<string>

using namespace std;

class Student //(1)修改student类中各数据成员和成员函数的访问限定符,并观察发生的现象
{
public: 
	Student(int n, string nam, char s) ;
	void show();
	~Student( ){ } 
protected: 
	int num;
	string name;
	char sex ; 
};

class Student1 : public Student //(2)修改此处的继承方式,并观察发生的现象
{ public: 
	Student1(int n, string nam, char s, int a, string ad) ;
	void show1( );
	~Student1( ){ } 
 private: 
	int age; 
	string addr; 
};

Student :: Student(int n, string nam, char s) 
{	num = n;
	name = nam;
	sex = s; 
}
void Student :: show()
{	cout << "num: " << num << endl;
	cout << "name: " << name << endl;
	cout << "sex: " << sex << endl << endl;
}

Student1 :: Student1(int n, string nam, char s, int a, string ad) : Student(n, nam, s) 
{	age = a; 
	addr = ad;
}

void Student1 :: show1( )
{	cout << "num: " << num << endl;
	cout << "name: " << name << endl;
	cout << "sex: " << sex << endl;
	cout << "age: " << age << endl;
	cout << "address: " << addr << endl << endl;
}

int main( )
{	Student1 stud1(10010, "Wang-li", 'f', 19, "115 Beijing Road,Shanghai");
	Student1 stud2(10011, "Zhang-fun", 'm', 21, "213 Shanghai Road,Beijing");
	Student stud3(20010, "He-xin", 'm');
	stud1.show1( ); 
	stud2.show( ); 
	stud3.show( ); 
	system("pause");
	return 0;
}
/*
修改一:
把Student类中的成员改成私有的,则编译器提示错误为:error C2248: “Student::num”: 无法访问 private 成员(在“Student”类中声明)
说明继承方式虽然是公有继承但是私有成员还是私有的,只能他自己调用,别人无法使用它

修改二:
把继承方式改为protected,则编译器提示错误为: error C2247: “Student::show”不可访问,因为“Student1”使用“protected”从“Student”继承
说明说明受保护成员函数不能够被对象直接调用

修改三:
把继承方式改为private,则编译器提示错误为: error C2247: “Student::show”不可访问,因为“Student1”使用“private”从“Student”继承
说明说明私有成员函数和受保护成员函数一样,都不能被对象直接调用!


总结:

1.保护继承就是把基类原有的公用成员与保护起来,不让类外任意访问
2.私有继承就是将原来能被外界引用的成员隐藏起来,不让外界应用
3.公用的访问属性,派生类内和派生类外都可以访问,
受保护的,派生类内可以访问,派生类外不能访问
私有的,派生类内可以访问,派生类外都不能访问
不可访问的,派生类内外都不能访问

*/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值