继承:继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更容易。这样做,也达到了重用代码功能和提高执行时间的效果。一个类可以派生自多个类,这意味着,它可以从多个基类继承数据和函数。定义一个派生类,我们使用一个类派生列表来指定基类。类派生列表以一个或多个基类命名,形式如下:
1 class student:public people //单个继承 2 { 3 }; 4 class student:public people,public kid //多个继承 5 { 6 };
如果不用访问修饰词(public、protected、private),则默认为private。关于继承后,类成员的访问权限如下:
- 公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。
- 保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。
- 私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。
一个派生类继承了所有的基类方法,但下列情况除外:
- 基类的构造函数、析构函数和拷贝构造函数。
- 基类的重载运算符。
- 基类的友元函数。
1 #include <iostream> 2 using namespace std; 3 4 class student 5 { 6 public: 7 static int i; //静态变量 8 int getSum(string Name) 9 { 10 if (name == Name){return math + chiness + english;} 11 else{return -1;} 12 } 13 student(); 14 private: 15 string name; 16 int math; 17 int chiness; 18 int english; 19 }; 20 int student::i = 0; //静态变量:要在类外通过"::"初始化。 21 student::student() //用构造函数初始化变量 22 { 23 name = "jim"; 24 math = 95; 25 chiness = 93; 26 english = 98; 27 i++; 28 } 29 30 class jim : student //student的派生类jim拥有基类的所有的成员。 31 { 32 public: 33 int getresu(string name) 34 { 35 return this->getSum(name); //通过this指针访问继承自student的getsum函数 36 } 37 static int retu() 38 { 39 return i; //访问继承自student的静态变量 40 } 41 }; 42 43 int main() 44 { 45 cout << " retu = " <<jim::retu() << endl; //在没有创建对象时,通过::访问类的静态成员 46 jim j; 47 cout << "getresu = " << j.getresu("jim") << endl; 48 cout << " retu = " << j.retu() << endl;50 }
结果为:
retu = 0 getresu = 286 retu = 1