C++面向对象入门(二十五)继承中的构造函数
作者:互联网
1, 派生类不会继承基类的构造
2, 派生类可以调用基类的构造
3, 使用初始化列表调用基类的构造
代码示例
#include<iostream> using namespace std; /* 1, 派生类不会继承基类的构造 2, 派生类可以调用基类的构造 3, 使用初始化列表调用基类的构造 */ class Biologically; class Rider; class Rider { protected: string name; double kickValue; double punchValue; string driver; string model; double HP; double power; double defend; public: Rider(string, string, string, double, double); virtual void riderKick(Biologically bio); virtual void riderPunch(Biologically bio); void kickAndPunch() { cout << "Base Member kick value:" << kickValue << ", punch value:" << punchValue << endl; } }; class ZeroOne: public Rider { public: string dad; //派生类自己的构造函数的初始化列表中调用基类的构造函数 ZeroOne(string name, string model, string driver, double kv, double pv) :Rider(name, model, driver, kv, pv) { dad = "Hiden Sereo"; } void realizing() { model = "Realizing Hopper"; kickValue = 114.7; punchValue = 59.1; } }; class Biologically { public: double HP; Biologically():HP(10000000){} ~Biologically() { cout << "Biologically died!"; } }; void Rider::riderKick(Biologically bio) { bio.HP -= kickValue * 1000 * 10000; if (bio.HP < 0) delete &bio; } void Rider::riderPunch(Biologically bio) { bio.HP -= kickValue * 1000 * 5000; if (bio.HP < 0) delete &bio; } Rider::Rider(string name,string model,string driver, double kv, double pv):name(name), model(model),driver(driver),kickValue(kv),punchValue(pv) {} int main() { Biologically bio; Rider rider("Zio", "one phase", "Tokiwa Sougo", 19.0, 8.2); ZeroOne aruto("Zero One", "Rising Hopper", "Hiden Aruto", 27.2, 8.9); //使用子类对象给基类变量赋值并访问基类成员 rider.kickAndPunch(); aruto.kickAndPunch(); rider = aruto; rider.kickAndPunch(); //派生类对象的地址复制给基类指针变量并访问基类成员 Rider *r1 = &aruto; r1->kickAndPunch(); //派生类用于基类引用初始化并访问基类成员 Rider &r2 = aruto; r2.kickAndPunch(); system("pause"); return 0; }
标签:string,double,派生类,C++,面向对象,构造,基类,Rider,构造函数 来源: https://www.cnblogs.com/RGBTH/p/13591182.html