C++ 面向对象

来源:互联网 发布:maka软件官网 编辑:程序博客网 时间:2024/06/06 09:01

C++ 面向对象 :

类 & 对象 :

C++ 类定义 :

它定义了类的对象包括了什么属性,以及可以执行哪些操作( 调用函数 ) .

class Box{   public:      double length;   // 长度      double breadth;  // 宽度};

关键字 public 确定了类成员的访问属性. 在类对象作用域内,类的外部是可访问的 .
也可以指定类的成员为 private 或 protected

  • public : 外部可以访问 .
  • private : 外部无法访问 .
  • protected : 该类的子类可以访问 , 外部无法访问.

这里写图片描述

定义 C++ 对象 :

Box Box1;          // 声明对象 Box1,类型为 BoxBox Box2;          // 声明对象 Box2,类型为 Box

C++ 继承 :

继承是依据另一个类来定义一个类 , 不需要重新写重复的属性和函数,只需指定新建的类继承了一个已有的类 , 这个已有的类称为基类,新的类称为派生类 .

假设现在有 基类 - Shape,派生类 - Rectangle,如下所示:

#include <iostream>using namespace std;// 基类class Shape {   public:      void setWidth(int w)      {         width = w;      }      void setHeight(int h)      {         height = h;      }   protected:      int width;      int height;};// 派生类class Rectangle: public Shape{   public:      int getArea()      {          return (width * height);       }};int main(void){   Rectangle Rect;   Rect.setWidth(4);   Rect.setHeight(5);   // 输出对象的面积   cout << " 面积 = " << Rect.getArea() << endl;   return 0;}

结果 :

 面积 = 35

继承类型 :

当一个类派生自基类,该基类可以被继承为 public、protected 或 private 几种类型 .
通常使用 public 继承 , 不使用 protected 或 private 继承

  • 公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问 .
  • 保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员 .
  • 私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员 .

★多继承 :

C++ 类可以从多个类继承成员

#include <iostream>using namespace std;// 基类 Shapeclass Shape {   public:      void setWidth(int w)      {         width = w;      }      void setHeight(int h)      {         height = h;      }   protected:      int width;      int height;};// 基类 PaintCostclass PaintCost {   public:      int getCost(int area)      {         return area * 70;      }};// 派生类class Rectangle: public Shape, public PaintCost{   public:      int getArea()      {          return (width * height);       }};int main(void){   Rectangle Rect;   int area;   Rect.setWidth(5);   Rect.setHeight(7);   area = Rect.getArea();   // 输出面积   cout << "面积 = " << Rect.getArea() << endl;   // 输出花费   cout << "花费 = " << Rect.getCost(area) << endl;   return 0;}

结果 :

面积 = 35花费 = 2450
1 0
原创粉丝点击