首页 > 编程 > C++ > 正文

C++访问权限和继承方式

2019-11-08 03:16:17
字体:
来源:转载
供稿:网友

#include<iostream>#include<string>using namespace std;class Person{PRotected:	string name;private:	int age;public:   //常量引用不可以通过函数修改实参,也就是说名字是确定的,不会被改变	Person(const string& con_name,int con_age)		:name(con_name),age(con_age){}	void show()	{   //基类成员函数可以访问public、protected、private成员		cout << name << endl;		cout << age << endl;	}};             //三种继承方式不影响子类对父类的访问权限,子类对父类的访问权限只看父类的访问控制权class Teacher :/*public*/ /*protected*/ private Person{private:	string title;public:	Teacher(const string& con_name,int con_age,const string& con_title)		:Person(con_name,con_age),title(con_title){}	void showteacher()	{		show();   //子类调用公有制成员函数		cout << name << endl;  		//cout << age << endl;   age在基类中是私有成员,子类不可以访问  基类受保护成员可以被子类成员函数访问		cout << title << endl;	}};int main(){	string name = "卢宪";	//string name={"卢宪"};	//Person physicist(name, 63);	Person person("卢宪", 63);  //普通引用不能绑定常量,常量引用可以绑定常量也可以绑定变量,也就是说如果要用引用,尽量用常量引用	person.show();//为什么person.后面只出现show?  因为从对象去访问相等于外部访问,外部访问只能是public类型		Teacher physicist("卢宪", 63, "物理主任");	physicist.showteacher();//为什么physicist.后面出现shou和teachershow? 	                        //因为子类不管是哪种继承方式,父类public权限依然遗留下来	system("pause");	return 0;}//私有成员函数被类中其他成员函数调用,不对外提供接口,当然也不可以有对象访问//为了防止外部访问,可将数据设置成private//继承方式是为了控制子类的调用(用户)方对父类的访问权限


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选