C++类的继承

来源:互联网 发布:鹤壁公务员网络培训 编辑:程序博客网 时间:2024/06/05 07:45

在C++中,可以通过已有的一个类派生出一个新类,称为继承。这是C++中一个重要特性。通过继承,实现代码重用。在修改程序功能时会变得更快捷。

 还是以上篇文章中的person类为例。假如我现在要求这个类再加一些成员或成员函数。当然我们可以修改person.h 和person.cpp中类的声明和定义。还有就是让person类派生一个新类。派生很简单:

   class myPerson : public Person {

}

 于是再加两个文件,myPerson.h 和myPerson.cpp,

myPerson.h中放声明:

#ifndef MYPERSON_H_H
#define MYPERSON_H_H
#include "person.h"
class myPerson : public Person {
private:
           float weight;
public:
           float GetWeight() const;
};
#endif

-----------------------------------------------------------

myPerson.cpp中放定义:

#include "stdafx.h"
#include "myperson.h"
float myPerson::GetWeight() const
{
    return weight;
}

----------------------------------------------------------

但我们会发现一个新的问题,如何访问weight这个成员呢?

像这样 myPerson me;

      me.weight=50 ;  //这样会错,因为weight是private,当然把 weight修改为public就行了。但违反了数据隐藏的原则。

     还有 me.GetWeight() 会返回什么呢??

实际上,我们缺少了构造函数。

当基类没有构造函数时,派生类更不可能有。因为派生类的构造必须先调用基类的构造函数。通过基类的构造函数初始化从它那继承的所有成员变量。

因此,我们要分别添加两个类的构造函数才能使用myPerson这个类。

先在person.h中加入构造函数     Person() {age=20;}

再在myPerson.h中加入构造函数  myPerson(): Person(){}
                                           myPerson(float a): Person(){weight=a;}

OK,可以测试派生的类了.

#include "stdafx.h"
#include "person.h"
#include "myperson.h"
#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 myPerson me(55.0);
int i=me.GetWeight();
cout<<"我的体重是:"<<i<<endl;
system("pause");
return 0;
}

原创粉丝点击