【C++】公有_保护_私有_继承—代码学习记录

//继承
#include<iostream>
#include<string>
using namespace std;
// 基类people
class people {
private:
	int number;
	string name;
	int age;
protected:
	void fun();
public:
	people(int num, string n, int a);
	~people() { cout << "people类被析构" << endl; }
	void getpeople();
};
people::people(int num, string n, int a) {
	this->number = num;
	this->name = n;
	this->age = a;
}
void people::getpeople() {
	cout << "number:" << this->number << "name:" << this->name << "age:" << this->age << endl;
}
void people::fun() {
	cout << "This is people protected" << endl;
}
// 公有继承
// 基类公有和保护成员的访问属性在派生类中不变
class student : public people{
private:
	int grade;
protected:
	void fun2();
public:
	student(int grade, int num, string name, int a);
	~student();
	void getstudent();
};
void student::fun2() {
	this->fun();	// 访问基类保护类成员
	cout << "This is student protected" << endl;
}
student::student(int grade, int num, string name, int a) : grade(grade), people(num, name, a) {}
student::~student() {
	cout << "student 类被析构" << endl;
	//不用手动调用基类析构函数,系统会自己调用
}
void student::getstudent() {
	this->getpeople();		// 访问基类公有成员
	cout << "grade:" << this->grade << endl;
}
// 保护继承
// 基类公有成员和保护成员都以保护成员身份出现在派生类中,基类私有成员不可直接被派生类访问
// 派生类可以访问保护类,外部使用者无法访问
class teacher :protected people {
private:
	int year;
protected:
	void fun3() { cout << "This is teacher protected"; };
public:
	teacher(int year, int num, string name, int a) :year(year), people(num, name, a) {}
	~teacher() { cout << "teacher类被析构" << endl;; }
	void getteacher();
};
void teacher::getteacher() {
	this->getpeople();	//调用基类继承而来保护类
	// this->fun(); 可以
	cout << "year:" << year << endl;
}

//私有继承
//基类公有和保护成员以派生类私有成员身份出现,只能被派生类访问
//与保护继承的异同
//同:都只能被派生类访问,不能被外部成员访问
//异:派生类作为基类继续派生时,私有成员会被隐藏,不能被派生类的派生类访问,但是公有成员可以
class college :private people {
private:
	int score;
protected:
	int fun4() { cout << "This is college protected" << endl; }
public:
	college(int score, int num, string name, int a) :score(score), people(num, name, a) {}
	~college() { cout << "college 类被析构" << endl; }
	void getcollege();
};
void college::getcollege() {
	this->getpeople();	//访问继承来的私有成员
	cout << "score:" << score << endl;
}

int main() {
	student zhang(3, 1, "xiaozhang", 18);
	zhang.getpeople();		//外部访问由基类公有继承而来的派生类公有成员
	zhang.getstudent();		//访问派生类的公有成员
	// zhang.fun();  不可访问保护类成员(由基类公有继承而来)
	// zhang.fun2(); 类外不能访问保护类成员
	teacher yi(10, 2, "xiaoyi", 22);
	yi.getteacher();	//派生类公有
	// yi.fun3();  不能调用派生类保护成员
	// yi.getpeople();	  不能调用基类保护继承来的保护成员
	college xing(100, 3, "xiaoxing", 19);
	xing.getcollege();	//自己的公有成员
	// xing.getpeople();	//不能访问继承来的私有成员
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值