1. 什么是继承?
-
基类
(class Animal)
可以有多个派生类(class Dog :public Animal)
class Animal //基类 { public: string name = "123"; int age; }; class Dog :public Animal //派生类 { }; int main() { Dog a; cout << a.name; //123 }
-
连续派生时(如果 Dog 由 Mammal 派生而来,而 Mammal 又是由 Animal 派生的),派生类将继承其所有基类的函数和数据
-
派生类可以改公有的基类函数为私有,此后派生都将保持私有
2. 如何从一个类派生出另一个?
-
创建派生类的对象时,将按顺序调用多个构造函数
-
创建派生类对象(Dog dog1)时:先调用基类(Animal)构造函数,再调用派生类自己的(Dog)构造函数
销毁派生类对象(Dog dog1)时:先调用派生类自己的(Dog)析构函数,再调用基类(Animal)析构函数
class Animal //基类 { public: Animal() { cout << "Animal基类的构造函数" << endl; }; ~Animal() { cout << "Animal基类的~析构函数" << endl; }; }; class Dog :public Animal //派生类 { public: Dog() { cout << "Dog派生类的构造函数" << endl; }; ~Dog() { cout << "Dog派生类的~析构函数" << endl; }; }; int main() { Dog dog1; //Animal基类的构造函数 //Dog派生类的构造函数 //Dog派生类的~析构函数 //Animal基类的~析构函数 }
3. 如何在派生类中访问基类的成员函数?
class Mammal { public: void Move() {cout << "Move()" << endl;} void Move(int a) { cout << "Move()" << a << endl; } }; class Dog :public Mammal { public: void Move() { cout << "Dog Move()" << endl; } }; int main() { Mammal M1; Dog d1; M1.Move(3); //子类调用父类的成员函数 d1.Mammal::Move(6); return 0; }
4. 如何重写基类的成员函数
-
重写函数时,函数名、参数列表、返回类型必须和基类成员函数一致
class Mammal //基类 { public: Mammal() { cout << "Mammal()" << endl; } ~Mammal() { cout << "~Mammal()" << endl; } void speak()const { cout << "speak()" << endl; } }; class Dog :public Mammal //派生类 { public: Dog() { cout << "Dog()" << endl; } ~Dog() { cout << "~Dog()" << endl; } //子类重写了父类的成员函数speak(),隐藏了基类的同名函数 void speak()const { cout << "Dog speak()" << endl; } }; int main() { Mammal M1; //Mammal() Dog d1; //Mammal() Dog() M1.speak(); //speak() d1.speak(); //Dog speak() return 0; //~Dog() ~Mammal() ~Mammal() }
-
重载和重写
术语相似,重载是创建多个同名但不同的函数;重写是在派生类中修改基类函数
5. 什么是受保护访问,如何使用它?
访问权限
访问 | public | protected | private |
---|---|---|---|
同一个类 | √ | √ | √ |
派生类 | √ | √ | |
外部的类 | √ |
class Animal //基类 { protected: int b1 = 10; int b2 = 20; public: int a_test = b1 + b2; }; class Dog :public Animal {}; //派生类 int main() { Dog dog1; cout << dog1.a_test << endl; //30,派生类(Dog)访问基类(Animal)的 protected数据 }
原文地址:http://www.cnblogs.com/ZWJ-zwj/p/16812674.html
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,请务用于商业用途!
3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员!
8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载
声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性