码迷,mamicode.com
首页 > 编程语言 > 详细

011_linuxC++之_继承的引入

时间:2018-09-23 18:14:14      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:c++   对象   clu   on()   lap   面向   splay   space   程序   

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

(二)引入继承程序

技术分享图片
 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类中的成员函数

 

011_linuxC++之_继承的引入

标签:c++   对象   clu   on()   lap   面向   splay   space   程序   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!