C++类面对对象

面对对象的程序设计:

对象构成:(解释:面对对象更接近人的思维)

{
①属性
②行为
};

类:(解释:具有相同属性和行为的对象)

(1)抽象:简单来说就是定义一个类的过程。

(2)封装:(解释:定义类的时候,用大括号将其当作为一个整体)
最简单的结构
class student {
//访问属性;
成员变量;
成员函数;
};

//类定义时:可将个别属性(成员变量)和功能(成员函数)声明为private(“私有”)访问属性。//

//目的:设定除了类的成员函数,其他函数是不能直接访问这些被声明为private访问属性的成员。//

(3)继承(解释:代码可以重复利用):就是所谓的“子类”,比如:已经建立一个A类,在建立一个B类,只需在A的基础上添加一些行为和属性。

(4)多态:不同的对象接受同一个命令,通过各自不同的动作达到实现目标的现象。

#include <iostream> 
using namespace std;
 
class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      virtual 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;
}

输出:

Rectangle class area :
Triangle class area :
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值