(一)面向对象程序设计中最重要的一个概念是继承。继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更容易。这样做,也达到了重用代码功能和提高执行时间的效果。
(二)引入继承程序
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Person {
private:
char *name;
int age;
public:
~Person()
{
cout << "~Person()"<<endl;
if (this->name) {
cout << "name = "<<name<<endl;
delete this->name;
}
}
void setName(char *name)
{
if (this->name) {
delete this->name;
}
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
int setAge(int a)
{
if (a < 0 || a > 150)
{
age = 0;
return -1;
}
age = a;
return 0;
}
void printInfo(void)
{
cout<<"name = "<<name<<", age = "<<age<<endl;
}
};
class Student : public Person {
};
int main(int argc, char **argv)
{
Student s;
s.setName("zhangsan");
s.setAge(16);
s.printInfo();
return 0;
}
person.cpp
(三)运行结果
(四)解析程序
- 在程序中类Student并没有初始化,但是他继承了Person所以可以使用Person类中的成员函数