011_linuxC++之_继承的引入

(一)面向对象程序设计中最重要的一个概念是继承。继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更容易。这样做,也达到了重用代码功能和提高执行时间的效果。

(二)引入继承程序

 1 #include <iostream>
 2 #include <string.h>
 3 #include <unistd.h>
 4 
 5 using namespace std;
 6 
 7 class Person {
 8 private:
 9     char *name;
10     int age;
11 
12 public:
13 
14     ~Person()
15     {
16         cout << "~Person()"<<endl;
17         if (this->name) {
18             cout << "name = "<<name<<endl;
19             delete this->name;
20         }
21     }
22 
23     void setName(char *name)
24     {
25         if (this->name) {
26             delete this->name;
27         }
28         this->name = new char[strlen(name) + 1];
29         strcpy(this->name, name);
30     }
31     int setAge(int a)
32     {
33         if (a < 0 || a > 150)
34         {
35             age = 0;
36             return -1;
37         }
38         age = a;
39         return 0;
40     }
41     void printInfo(void)
42     {
43         cout<<"name = "<<name<<", age = "<<age<<endl;
44     }
45 };
46 
47 class Student : public Person {
48 };
49 
50 
51 int main(int argc, char **argv)
52 {
53     Student s;
54     s.setName("zhangsan");
55     s.setAge(16);
56     s.printInfo();
57 
58     return 0;
59 }
person.cpp

(三)运行结果

(四)解析程序

1. 在程序中类Student并没有初始化,但是他继承了Person所以可以使用Person类中的成员函数

 

原文地址:https://www.cnblogs.com/luxiaoguogege/p/9693096.html