类的继承

类的继承

公有继承

当类的继承方式为公有继承时,基类的公有成员和保护成员的访问属性在派生类中不变,而基类的私有成员不可直接访问。派生类的其它成员可以直接访问基类的公有成员和保护成员,派生类的对象无法访问基类的保护成员和私有成员。

#include<iostream>
#include<cmath>
using namespace std;
class Parent {
public:
	void initParent(int x, int y) {
		this->x = x;
		this->y = y;
	}
	int GetX() { return x; }
	int GetY() { return y; }
protected:
	int y;//保护成员
private:
	int x;
};
class Person :public Parent{ //公有继承
public:
	void initPerson(int x, int y, int w, int h) {
		initParent(x, y);//在子类使用父类的函数成员
		this->w = w;
		this->h = h;
	}
	int GetW() { return w; }
	int GetH() { return h; }
private:
	int w, h;
};
void main() {
	Person b;
	b.initPerson(1, 2, 3, 4);
	cout << b.GetX() << endl;
	cout << b.GetY() << endl;
	cout << b.GetW() << endl;
	cout << b.GetH()<< endl;
	system("pause");
}

运行效果:
4.1.png

保护继承

当类的继承方式为保护继承时,基类的公有成员和保护成员都以保护成员的身份出现在派生类中,而基类的私有成员不可直接访问。派生类的其他成员可直接访问基类的公有和保护成员,通过派生类的对象无法访问基类的公有和保护成员。

沿用之前的代码改为保护继承后的运行效果:
4.2.jpg
可以看到此时通过对象不能再访问父类的成员函数了
修改代码:

#include<iostream>
#include<cmath>
using namespace std;
class Parent {
public:
	void initParent(int x, int y) {
		this->x = x;
		this->y = y;
	}
	int GetX() { return x; }
	int GetY() { return y; }
protected:
	int y;//保护成员
private:
	int x;
};
class Person :protected Parent{ //保护继承
public:
	void initPerson(int x, int y, int w, int h) {
		initParent(x, y);//在子类使用父类的函数成员
		this->w = w;
		this->h = h;
	}
	void shoe() {
		cout << GetX() << endl;
		cout << GetY() << endl;//当声明为保护继承时,子类中任然可以使用父类的函数成员
	}
	int GetW() { return w; }
	int GetH() { return h; }
private:
	int w, h;
};
void main() {
	Person b;
	b.initPerson(1, 2, 3, 4);
	b.shoe();
	cout << b.GetW() << endl;
	cout << b.GetH()<< endl;
	system("pause");
}

运行效果
4.3.jpg

私有继承

当类的继承方式为私有继承时,基类中的公有成员和保护成员都以私有成员身份出现在派生类中,基类的私有成员不可直接访问。派生类的其它成员可以直接访问基类的公有和保护成员,派生类的对象无法访问基类的公有和保护成员。

沿用之前的代码改为私有继承后的运行效果:
4.4.jpg
同样通过私有继承后,不能再通过对象访问父类的成员函数。
修改后的代码:

#include<iostream>
#include<cmath>
using namespace std;
class Parent {
public:
	void initParent(int x, int y) {
		this->x = x;
		this->y = y;
	}
	int GetX() { return x; }
	int GetY() { return y; }
protected:
	int y;//保护成员
private:
	int x;
};
class Person :private Parent{ //私有继承
public:
	void initPerson(int x, int y, int w, int h) {
		initParent(x, y);//在子类使用父类的函数成员
		this->w = w;
		this->h = h;
	}
	void shoe() {
		cout << GetX() << endl;
		cout << GetY() << endl;//当声明为私有继承时,子类中任然可以使用父类的函数成员
	}
	int GetW() { return w; }
	int GetH() { return h; }
private:
	int w, h;
};
void main() {
	Person b;
	b.initPerson(1, 2, 3, 4);
	b.shoe();
	cout << b.GetW() << endl;
	cout << b.GetH()<< endl;
	system("pause");
}

运行效果:
4.5.png

posted @ 2019-10-13 17:40  tao4867  阅读(162)  评论(0编辑  收藏  举报