子类父类 构造函数析构函数

本文通过一个 C++ 示例展示了类的继承与方法重写的基本概念。其中包括了父类(Base)与子类(Derive)的定义,以及如何在子类中重写父类的方法。同时,还介绍了构造函数与析构函数的作用。

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

#include <iostream>  
using namespace std;//运算符的重载  
class Base//
{
public:
	int a;
	Base()
	{
		cout << "父类的不带参的构造函数调用" << endl;
	}
	Base(int a)
	{
		cout << "父类的带参数的构造函数调用" << endl;
	}
	~Base()
	{
		cout << "父类的析造函数调用" << endl;
	}
	void go()//父类  
	{
		cout << "父类的go()" << endl;
	}
	void go(int a)//父类  
	{
		this->a = a;
		cout << "父类的有参数的go()" << endl;
	}
};
//父类 = 基类  子类 = 派生类  
class Derive :public Base//学生,公有的继承  
{
public:
	Derive() :Base(10)//构造函数,继承父类  
	{
		cout << "子类的构造函数调用" << endl;
	}
	~Derive()
	{
		cout << "子类的析造函数调用" << endl;
	}
	void go()//重写这个go(),继承父类  
	{
		cout << "子类的无参数的go()" << endl;
	}
	void go(int a)//重写这个go(),继承父类  
	{
		cout << "子类的带参的go()" << endl;
	}
};
void main()
{
	{
		Derive child;
		child.go();//子类的go()  
		child.Base::go();//父类的go(),这个是子类调用父类的方法  
		child.go(10);
	}
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值