C++ 派生类与继承

为什么需要继承?

在编写大型程序时,往往有很多的类,每个类都有自己的数据成员和函数,但有些类之间的数据成员和函数却相同,为了节省代码量和工作时间,只需继承父类中的数据成员和函数即可。

继承就像是如基类为人,派生类为士兵、工人。基类人有很多特性,如名字、年龄。派生类继承了基类中的特性,派生类士兵、工人,同样也有名字、年龄和其他标识。

继承就是从先辈处得到属性和行为特征。类的继承就是新的类从已有类那里得到已有的特性。因此继承的本质代码复用。

继承分为public 公有继承、protected 保护继承、private私有继承

private和protected的区别

在继承中,基类的数据成员 private 在派生类与main函数中不可访问 ,protected 在派生类可访问main函数不可访问


派生类中,从基类继承来的成员的访问限定是什么?

派生类对象占用空间大小怎么计算? 

class A
{
public:
private:
	int mc;
};
class B : private A // 继承到派生类里面的成员访问限定 <= 继承方式
{
public:
private:
	int mf;
};

int main()
{
	B b;
	cout << "b sizeof = " << sizeof(b) << endl;
	getchar();
	return 0;
}

 

由于B继承了A ,因此B也就继承了A的成员变量 mc 。

派生类怎么初始化从基类继承来的成员呢?

class Base
{
public:
	Base(int a) :ma(a) { cout << "Base()" << endl; }
	~Base() { cout << "~Base()" << endl; }
protected:
	int ma;
};
class Derive : public Base
{
public:
	//“Base”: 没有合适的默认构造函数可用
	Derive(int data) :Base(data), mb(data) { cout << "Derive()" << endl; }
	~Derive() { cout << "~Derive()" << endl; }
private:
	int mb;
};

通过调用基类相应的构造函数进行初始化,派生类只会初始化自己的成员

重载,隐藏,覆盖(基类和派生类同名成员函数之间的关系)


重载:函数名  参数列表  作用域  =》 重载函数

隐藏:基类和派生类当中   函数名相同   =》 隐藏

覆盖/重写:基类和派生类当中  函数的返回值,函数名,参数列表都相同,而且基类的函数是virtual虚函数,那么称作覆盖关系

重载在这里不必多提主要谈谈隐藏和覆盖

class Base
{
public:
	Base(int a) :ma(a) { cout << "Base()" << endl; }
	~Base() { cout << "~Base()" << endl; }
	void show() { cout << "Base::show()" << endl; }
	void show(int i) { cout << "Base::show(int)" << endl; }
protected:
	int ma;
};
class Derive : public Base
{
public:
	//“Base”: 没有合适的默认构造函数可用
	Derive(int data) :Base(data), mb(data) { cout << "Derive()" << endl; }
	~Derive() { cout << "~Derive()" << endl; }
	void show()
	{
		cout << "Derive::show()" << endl;
	}
private:
	int mb;
};
int main()
{
	Derive d(10);
//	d.show(20); // “Derive::show”: 函数不接受 1 个参数
	d.show();
	d.Base::show();

	getchar();
	return 0;
}

当我定义一个派生类对象后,需要现在调用基类的构造函数构造初始化继承来的成员变量,然后调用派生类构造函数初始化派生类成员变量。当我调用同名show函数时,调用的是派生类的show函数,如果需要调用基类的show函数时,需要加作用域限定符。

继承是一个由上到下的结构 。继承结构中 默认支持下到上的类型转换

class Base
{
public:
	Base(int a) :ma(a) { cout << "Base()" << endl; }
	~Base() { cout << "~Base()" << endl; }
	void show() { cout << "Base::show()" << endl; }
	void show(int i) { cout << "Base::show(int)" << endl; }
protected:
	int ma;
};
class Derive : public Base
{
public:
	Derive(int data) :Base(data), mb(data) { cout << "Derive()" << endl; }
	~Derive() { cout << "~Derive()" << endl; }
	void show() { cout << "Derive::show()" << endl; }
private:
	int mb;
};
int main()
{
	// 继承结构  从上到下的结构  
	Base b(10);
	Derive d(20);
	d = b;  //    错误  派生类对象 = 基类对象  no   上 =》 下
	b = d;  // 正确     基类对象 = 派生类对象  yes  下 =》 上

	Base *pb = &d; //    基类指针/引用 = 派生类对象  yes   下 =》 上
	pb->show(10);

	Derive *pd = &b; //   错误   派生类指针/引用 = 基类对象 上 =》 下
	pd->show();  // mb

	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhangfei5354/article/details/89422705
今日推荐