概念
是面向对象程序设计是代码可以复用的最重要的手段,它允许程序员在保持原有的类的特性的基础下进行拓展,增加功能。 这样产生的类被称为派生类;
class Person
{
public:
void Print()
{
cout << "name:" << _name << endl; cout << "age:" << _age << endl;
}
protected:
string _name = "peter"; // 姓 名
int _age = 18; // 年 龄
};
// 继承后父类的Person的成员(成员函数+成员变量)都会变成子类的一部分。这里体现出了Student和Teacher复用了Person的成员。下面我们使用监视窗口查看Student和Teacher对象,可以看到变量的复用。调 用Print可以看到成员函数的复用。
class Student : public Person
{
protected:
int _stuid; // 学 号
};
class Teacher : public Person
{
protected:
int _jobid; // 工 号
};
int main()
{
Student s; Teacher t; s.Print();
t.Print();
return 0