C++关于构造函数可向父类或者本类传参的讲解
前面我们学习了C++使用初始化列表的方式来初始化字段的方法: https://www.52php.cn/article/153032.htm 这一节的原理和前面的差不多。 在C++的构造函数中,子类继承父类,那么,在创建一个子类成员时,可以同时向父类或者子类的构造函数进行传参,实现方法如下: 写一个例子:mul_argc.c #include #include 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 ; } 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程之家的支持。如果你想了解更多相关内容请查看下面相关链接 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |