C++基础知识整理十一(派生类的构造和析构函数 多重继承)

本文通过C++代码示例详细介绍了单继承和多重继承的概念及实现过程。在单继承中,子类继承自一个父类,并在构造过程中先调用基类构造函数再执行自己的构造函数。而在多重继承中,一个类可以从多个基类继承属性和方法,示例代码展示了如何在构造函数中调用不同基类的构造函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,单继承方式

AbStudent.cpp代码如下: 

#include "pch.h"
#include <iostream>
//#include "CPeople.h"
#include "CStudent.h"

int main(int argc ,char* argv[])
{
	CStudent stu;
	return 0;
}

CPeople.cpp代码如下: 

#include "pch.h"
#include "CPeople.h"
#include<iostream>
using namespace std;


CPeople::CPeople()
{
	cout << "people" << endl;
}


CPeople::~CPeople()
{
}

CStudent.cpp代码如下: 

#include "pch.h"
#include "CStudent.h"
#include "iostream"
using namespace std;

//可以看到CStudent首先执行基类的构造函数然后再执行自己类的构造函数
CStudent::CStudent()
{
	cout << "student" << endl;
}


CStudent::~CStudent()
{
}

CPeople.h代码如下: 

#pragma once
class CPeople
{
public:
	CPeople();
	~CPeople();
private:
	char name[10];
};

CStudent.h代码如下: 

#pragma once
#include "CPeople.h"
class CStudent :
	public CPeople
{
public:
	CStudent();
	~CStudent();
private:
	char no[10];
};

运行结果 :

 以上可以看到CStudent首先执行基类的构造函数然后再执行自己类的构造函数

2,多重继承 

 

mulStudent.cpp代码如下

#include "pch.h"
#include "CXiao.h"

int main(int argc , char* argv[])
{
	CXiao xiao((char*)"A003", (char*)"li", (char*) "prof");
	xiao.display();
	return 0;
}

cstudent.cpp代码如下

#include "pch.h"
#include "CStudent.h"
#include <iostream>
using namespace std;


CStudent::CStudent(char* no ,char* name)
{
	strcpy_s(this->no , no);
	strcpy_s(this->name , name);
}


CStudent::~CStudent()
{
}

char* CStudent::getNo()
{
	return no;
}
char* CStudent::getName()
{
	return name;
}

cteacher.cpp代码如下

#include "pch.h"
#include "CTeacher.h"
#include <iostream>
using namespace std;


CTeacher::CTeacher(char* position)
{
	strcpy_s(this->position , position);
}


CTeacher::~CTeacher()
{
}

char* CTeacher::getPosition()
{
	return position;
}

cxiao.cpp代码如下

#include "pch.h"
#include "CXiao.h"
#include <iostream>
using namespace std;


CXiao::CXiao(char* no, char* name, char* position):CTeacher(position),CStudent(no,name)
{
}


CXiao::~CXiao()
{
}

void CXiao::display()
{
	cout << "name:" << getName() << ",no :" << getNo() << ",positon:" << getPosition() << endl;
}

cstudent.h代码如下

#pragma once
class CStudent
{
public:
	CStudent(char* no ,char* name);
	~CStudent();
private:
	char no[10];
	char name[10];
public:
	char* getNo();
	char* getName();
};

cteacher.h代码如下

#pragma once
class CTeacher
{
public:
	CTeacher(char* position);
	~CTeacher();
private:
	char position[10];
public:
	char* getPosition();
};

cxiao.h代码如下

#pragma once
#include "CTeacher.h"
#include "CStudent.h"

class CXiao:public CTeacher,public CStudent
{
public:
	CXiao(char* no, char* name, char* position);
	~CXiao();
public:
	void display();
};

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值