C++构造函数可向父类或者本类传参

前面我们学习了C ++使用初始化列表的方式初始化字段:

http://blog.csdn.net/morixinguan/article/details/74331335

这一节的原理和前面的差不多。

在C++的构造函数中,子类继承父类,那么,在创建一个子类成员时,可以同时向父类或者子类的构造函数进行传参,实现方法如下:

写一个例子:

mul_argc.c

#include <iostream>
#include <cstring>
using namespace std ; 
//英雄联盟类 
class Hero
{
	private :
	int blood ; 
	string name ;
	public :
	Hero(int blood = 100, string name = "man wang")
	{
		this->blood = blood ; 
		this->name = name ;
	}
	~Hero()
	{
		if(this->blood < 0){
			cout << "Hero blood error!\n" << endl ;
			return ;
		}
		cout << "Hero name is:" << this->name << endl ; 
		cout << "Hero blood is :" << this->blood << endl ;	
	}	
}; 
//德玛类,继承于英雄类 
class Dema : public Hero
{
	private :
	int blood ; 
	string name ;
	public :
	Dema(int blood , string name);
	~Dema();
};

//在实现子类的构造函数时,可以同时向父类的构造函数传参
//例如这个例子的 : Hero(58,JS),相当于向父类的构造函数传参

//当然,子类也可以给本类的的成员传参
Dema::Dema(int blood , string name) : Hero(89 , "JS") , blood(58) , name("dema")
{
	this->name = name ;
	this->blood = blood ; 
}

Dema::~Dema()
{
	if(this->name != "dema"){
		cout << "This Hero are no dema!" << endl;
		return ;
	}
	if(this->blood < 0){
		cout << "Dema blood error!\n" << endl ;
		return ;
	}
	cout << "Dmea name is:" << this->name << endl ; 
	cout << "Dema blood is :" << this->blood << endl ;	
}

int main(int argc , char **argv)
{
	Dema player1(79,"dema");
	return 0 ;
}
运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Engineer-Bruce_Yang

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值