C++继承和派生

继承的基本语法:class类名:继承方式 父类,继承方式 父类......可以写多个父类,示例如下

#include<iostream>
using namespace std;

class father
{

};

class mother
{

};

class son :public father, protected mother
{

};

int main()
{


	return 0;
}

继承后,父类中的属性子类也会有一份,继承方式一共有三种:公共继承(public),保护继承(protected),私有继承(private)

public继承方式后父类的public属性继承给子类还是public,protected属性还是protected

protected继承方式后父类的public和protected都变为子类的protected属性

private继承方式后父类的public属性和protected都变为子类的private

注:不论哪种继承方式父类的private属性都不可以被继承

继承下父类的属性需要子类调用父类的构造函数,案例如下

#include<iostream>
using namespace std;

class father
{
public:
	father(int a) :f(a){}
	int f;
};



class son :public father
{
public:
	son(int a,int b):father(a),s(b){}
	int s;
};

int main()
{
	son s(1, 2);


	return 0;
}

同名问题:最近原则,子类对象默认调用子类函数,若要调用父类的同名函数则需要加作用域分辨符,示例如下

#include<iostream>
using namespace std;

class father
{
public:
	void pt()
	{
		cout << "father" << endl;
	}
	
};


class son :public father
{
public:
	void pt()
	{
		cout << "son" << endl;
	}

};

int main()
{
	son s;
	s.pt();//最近原则调用子类自己的
	s.father::pt();//加了作用域分辨符::

	return 0;
}

构造对象时,先构造父类对象后构造子类对象,析构顺序相反,可以按如下代码验证

#include<iostream>
using namespace std;

class father
{
public:
	father()
	{
		cout << "调用father的构造函数" << endl;
	}
	~father()
	{
		cout << "调用father的析构函数" << endl;
	}
	
};


class son :public father
{
public:
	son()
	{
		cout << "调用son的构造函数" << endl;
	}
	~son()
	{
		cout << "调用son的析构函数" << endl;
	}
};

int main()
{
	son s;
	

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值