在private/protected 模块放置数据或者底层算法实现; 在public块提供对外接口,实现相应的功能调用; 类的封装案例 # include  <iostream> using  namespace  std; 
class  Stu  { public :  void  setAge ( const  int &  age)  { this -> age =  age; } const  int &  getAge ( )  const  { return  age; } private :  int  age; 
} ; int  main ( )  { Stu s1;  s1. setAge ( 20 ) ; cout <<  s1. getAge ( )  <<  endl; return  0 ; 
} 
将一个类的成员变量、成员函数,应用到另一个类中,实现复用; 支持多继承,同python一样;而 java 仅支持单继承; 继承修饰符public、protected、private; 若不写修饰符,则默认private继承; public继承,基类中的public、protected、private 保持不变; protected继承,基类中的public、protected、private 变为protected、protected、private private继承, 基类中的public、protected、private全部变为private; # include  <iostream> # include  <string> using  namespace  std; 
class  People  { 
public : string name; People ( const  string&  name,  const  int &  age,  const  double &  height)  { this -> name =  name; this -> age =  age; this -> height =  height; cout <<  "父类完成初始化"  <<  height <<  endl; } void  printName ( )  const  { cout <<  "name:"  <<  name <<  endl; } void  printAge ( )  const  { cout <<  "age:"  <<  this -> age <<  endl; } void  printHeight ( )  const  { cout <<  "height:"  <<  this -> height <<  endl; } protected : int  age; private : double  height; 
} ; 
class  Stu :  public  People {  
public :  int  num;  Stu ( const  string&  name,  const  int &  age,  const  double & heigh) :  People ( name,  age,  heigh) { this -> num =  102 ; } void  printAge ( )  const  { cout <<  "age:"  <<  this -> age <<  endl; } } ; int  main ( )  { string name =  "jack" ; int  age =  20 ; double  height =  23.5 ; Stu s1 ( name,  age,  height) ;   s1. printName ( ) ; s1. printAge ( ) ; s1. printHeight ( ) ;  return  0 ; 
} 
 
多个子类继承父类中的方法,分别实现方法的重写; 父类中采用 virtual  声明为虚函数; 函数体赋值为=0,则为纯虚函数; 在这里插入代码片