[toc]
类(Class) 类定义 1 2 3 4 5 6 class  className  {      };  
 
创建对象
1 2 3 4 5 6 7 8 class  className  {  ... }; int  main ()   {  int  i;    className c;  } 
 
类访问范围 私有:
1 2 3 4 5 6 7 8 9 10 class  Class1  {  int  num;    ... }; class  Class2  {  private :    int  num;   ... }; 
 
public & protected
1 2 3 4 5 6 7 8 9 class  myClass  {  int  num = 1 ;    protected :   int  count = 0 ;       public :    void  setNum ()  {   } }; 
 
类方法 类方法技能在类中直接定义 ,也可以先在类中声明 ,再在类外定义:
1 2 3 4 5 6 7 8 9 10 11 12 13 class  Rectangle  {  int  length;   int  width ;   public :   void  setLength (int  l)  {      length = l;   }      int  area ()  {     return  length * width ;    } };  
 
范围操作符::用于在类定义的外部定义类方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class  Rectangle  {  int  length;   int  width ;   public :         void  setLength (int  l)  ;   int  area ()  ; }; void  Rectangle::setLength (int  l)  {  length = l; } int  Rectangle::area ()  {  return  length * width ;  } 
 
构造器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include  <iostream>  #include  <string>  using  namespace  std ;class  Date  {  int  day;   int  month;   int  year;   public :      Date(){          day = 0 ;     month = 0 ;     year = 0 ;   }      void  printDate ()  {      cout  << "Date: "  << day << "/"  << month << "/"  << year << endl ;   } }; int  main ()  {     Date d;    d.printDate(); } 
 
this指针,this表示当前对象的指针。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #include  <iostream>  #include  <string>  using  namespace  std ;class  Date  {  int  day;   int  month;   int  year;   public :      Date(){          day = 0 ;     month = 0 ;     year = 0 ;   }         Date(int  day, int  month, int  year){          this ->day = day;     this ->month = month;     this ->year = year;   }      void  printDate ()  {      cout  << "Date: "  << day << "/"  << month << "/"  << year << endl ;   } }; int  main ()  {        Date d (1 , 8 , 2018 )  ;    d.printDate(); }