c++ 类

144 阅读1分钟
  • 类简单的实现
  • 默认是私有的
#include <iostream>

using namespace std;

class Box
{
    public:
          double length;   // 长度
          double breadth;  // 宽度
          double height;   // 高度
          //构造函数
          Box();
          //析构函数声明
          ~Box(); 
          //拷贝构造函数
          Box(const Box &p){
              length = p.length;
              //...
          }
          // 成员函数声明
          double get(void);
          void set(double len, double bre, double hei);
          // this使用 thiis->
          int compare(Box box)
          {
             return this->Volume() > box.Volume();
          }
          //静态函数
          static int getCount()
          {
             return objectCount;
          }
          // 友元函数 后面有使用
          friend void printWidth( Box box );
          // 重载 + 运算符,用于把两个 Box 对象相加
          Box operator+(const Box& b)
          {
             Box box;
             box.length = this->length + b.length;
             box.breadth = this->breadth + b.breadth;
             box.height = this->height + b.height;
             return box;
          }
    private:
          double width;  //即使是派生类也不能访问
    protected: 
          double width2; //只能内部访问
};
//构造函数
Box::Box(void)
{
    cout << "Object is being created" << endl;
}
//析构函数
Box::~Box(void)
{
    cout << "Object is being created" << endl;
}
//有元函数 请注意:printWidth() 不是任何类的成员函数 类似静态函数
void printWidth( Box box )
{
   /* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */
   cout << "Width of box : " << box.width <<endl;
}
// 成员函数定义
double Box::get(void)
{
    return length * breadth * height;
}
void Box::set(double len, double bre, double hei)
{
    length = len;
    breadth = bre;
    height = hei;
}
  • 派生1
//派生类
class SmallBox:Box // SmallBox 是派生类
{
   public:
      void setSmallWidth( double wid );
      double getSmallWidth( void );
};
// 子类的成员函数
double SmallBox::getSmallWidth(void)
{
    return width2 ;
}
void SmallBox::setSmallWidth( double wid )
{
    width2 = wid;
}
  • 派生2
#include <iostream> 
using namespace std;
 
class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Rectangle class area :" <<endl;
         return (width * height); 
      }
};
class Triangle: public Shape{
   public:
      Triangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Triangle class area :" <<endl;
         return (width * height / 2); 
      }
};
int main( )
{
   Shape *shape;
   Rectangle rec(10,7);
   Triangle  tri(10,5);
 
   // 存储矩形的地址
   shape = &rec; 
   // 调用矩形的求面积函数 area
   shape->area();
 
   // 存储三角形的地址
   shape = &tri;
   // 调用三角形的求面积函数 area
   shape->area();
   
   return 0;
}