26.C++类的继承与派生
2013-11-21 14:06
260 查看
/* 单继承: 如果只得到一个基类的遗传信息称为单继承; 如果得到多个基类的遗传信息称为多继承。 单继承是指从一个基类派生一个或多个派生类, 单继承派生类的定义格式如下: 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:56 f1.SkiColor(); f1.hairColor(); son s1; s1.weight();//weight: 75KG s1.display();//name:li zong,native:BeiJing,age:56 return 0; }
相关文章推荐