C++关于构造函数可向父类或者本类传参的讲解
时间:2021-04-29 10:57:54|栏目:C代码|点击: 次
前面我们学习了C++使用初始化列表的方式来初始化字段的方法:
https://www.jb51.net/article/153032.htm
这一节的原理和前面的差不多。
在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 ;
}
总结
上一篇:解决C++ 无法从void 转换为LRESULT的方法详解
栏 目:C代码
下一篇:VC多线程编程详解
本文地址:http://www.codeinn.net/misctech/111324.html






