本文主要是介绍26.C++类的继承与派生,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*单继承:如果只得到一个基类的遗传信息称为单继承;如果得到多个基类的遗传信息称为多继承。单继承是指从一个基类派生一个或多个派生类,单继承派生类的定义格式如下:class 派生类名:继承方式 基类名{派生类的新成员};继承方式:——公有继承(public)——私有继承(private)——保护继承(protected)如果没有明确指明继承方式,系统默认为私有继承*///派生类公有继承(public)例
#include <iostream>
#include <string.h>
class father //定义父类
{
public:father();//构造函数void SkiColor();void hairColor();void display();
protected:char name[20];char native[20];
private:int age;};
father::father()
{strcpy(name, "li zong");strcpy(native, "BeiJing");age=56;
}
void father::SkiColor()
{std::cout<<"the skin color is yellow"<<std::endl;
}
void father::hairColor()
{std::cout<<"the skin color is black"<<std::endl;
}
void father::display()
{std::cout<<"name:"<<name<<",native:"<<native<<",age:"<<age<<std::endl;
}class son:public father //定义子类
{
public:son();//构造函数void weight();
protected:char name[20];
private:int sonAge;
};
son::son()
{strcpy(name, "li yun");sonAge=20;
}void son::weight()
{std::cout<<"weight: 75KG"<<std::endl;
}int main(int argc, const char * argv[])
{father f1;f1.display();//name:li zong,native:BeiJing,age:56f1.SkiColor();f1.hairColor();son s1;s1.weight();//weight: 75KGs1.display();//name:li zong,native:BeiJing,age:56return 0;
}
这篇关于26.C++类的继承与派生的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!