123mcz / blog

0 stars 0 forks source link

继承多态 #10

Open 123mcz opened 5 hours ago

123mcz commented 5 hours ago

include

using namespace std; class Father { public: Father() { cout << "父类构造函数" << endl; } ~Father() { cout << "父类析构函数" << endl; } string name = "doc"; int age = 22; }; class Son : public Father { public: Son() { cout << "子类构造函数" << endl; } ~Son() { cout << "子类析构函数" << endl; } }; class Grandson : public Son { public:

}; void show(Father r) { cout << r.age << endl; } int main() { //Father类相当于a1 Son相当于a2 //同名 = 隐藏 //如何使用父类中被//隐藏的// xx.Father::custom(); 子类对象.父类名::父类函数(属性) //发生继承的时候,如果父类不存在默认构造函数怎么办?默认指函数里面没有参数 //1.再写一个默认构造函数 //2.子类构造函数上的初始化列表中手动使用父类的带参数的构造函数 Son xiaozhang,sss; cout << xiaozhang.age << endl; int a1[3] = { 11,3,1 }; int a2[5] = { 11,3,1,5,8 }; int a3[7] = { 11,3,1,5,8,22,66 }; //发生继承的时候 //1子类对象能给父类对象赋值 //2函数的参数类型如果是父亲类型的时候,该参数支持这个父类的任意子类对象 show(xiaozhang); show(sss); //3.如果一个容器的类型是父类类型的话,该容器能存这个父类的任意子类对象 Father arr[2]; arr[0] = xiaozhang; arr[1] = sss;

}

123mcz commented 5 hours ago

include

using namespace std;

include

class Monster { public: int hp = 0; std::string name = ""; virtual void skill() { std::cout << "技能" << std::endl; } };

class Giant : public Monster { public: };

class Gebilin : public Monster { public: };

class Orc : public Monster { public: int hp = 15; void skill() { std::cout << "3" << std::endl; } }; void show(Monster m) { m->skill(); } int main() { //多态—1函数重载也叫做静态联编 2虚函数virtual也叫做动态联编 //使用virtual的核心要点三同 返回值 函数名 参数都相同 //怎么动态联编? //只需要在父类的函数前加virtual关键字即可 //孩子有优先用孩子的,没有就用父亲的 //父亲的指针保存孩子对象的地址的时候,自动使用孩子里的虚函数 //父亲数组里面保存孩子对象的地址时候,自动使用孩子里的虚函数 //函数参数是父亲指针,但是传递参数是孩子对象,自动使用孩子里的虚函数 /Monster p = &m1; p->skill(); return 0;///父亲的指针保存孩子对象的地址的时候,自动使用孩子里的虚函数 Giant m1; Gebilin m2; Orc m3; Monster a[3]; a[0] = &m1; a[1] = &m2; a[2] = &m3; for (int i = 0; i < 3; i++) { a[i]->skill(); } show(&m1); //函数参数是父亲指针,但是传递参数是孩子对象,自动使用孩子里的虚函数 cout << m3.Monster::hp << endl; }