zoukankan      html  css  js  c++  java
  • c++类的组合(一)

      该笔记会在以后可能有所修改,完善该笔记。该笔记是自学c++结合博客中几篇类的组合的总结加自己的观点。

      类的组合这种思想是借用工程中的零部件组合的思想。比如,一条鱼这个类可以是尾巴,鱼头等等类组成。当然由于类中的成员数据由类的行为访问。而也正是可以将行为的结果提供给鱼这个类。这样实现了分工的思想。提高了效率。

    下面是博客中最常见的例子。

    功能是计算两个点之间的距离。

    #include<iostream>
    #include <cmath>
    using namespace std;
    /*_________________点的类的声明_____________________________________*/
    class point
    {
    public:
     point();  //无参数构造函数
     point(int xx,int yy);  //带参数的构造函数
     point(point &refcar);  //拷贝构造函数
     ~point();     //析构函数
     int getx();
     int gety();
    private:
     int x;
     int y;
    };
    point::point()
    {
    }

    point::point(int xx, int yy)
    {
     x = xx;
     y = yy;
    }

    point::point(point &refcar)
    {
     cout << "拷贝成功!" << endl;
     x = refcar.x;
     y = refcar.y;
    }

    point::~point()
    {
     static int i = 0;
     if (i == 1)
     {
      system("pause");
     }
     i++;
    }

    int point::getx()
    {
     return x;
    }

    int point::gety()
    {
     return y;
    }

    /*_____________________线的类的声明,类的组合___________________________________________*/
    class line
    {
    public:
     line();
     line(point p1, point p2);  //线的构造函数进行组合
     line(line &l);     //拷贝函数
     double getLen();
    private:
     point pp1, pp2;
     double len;
    };

    line::line()
    {
    }

    line::line(point p1, point p2) :pp1(p1), pp2(p2)
    {
     double x = static_cast<double>(pp1.getx() - pp2.getx()); //使用static_cast进行强制转化
     double y = static_cast<double>(pp1.gety() - pp2.gety()); //使用static_cast进行强制转化
     len = sqrt(x*x + y*y);
    }

    line::line(line &l) :pp1(l.pp1), pp2(l.pp2)
    {
     len = l.getLen();
     cout << "复制成功!";
    }

    double line::getLen()
    {
     return len;
    }

    /*_________________________________main_________________________*/

    int main()
    {
     point myp1(4, 5), myp2(5, 6);
     line line(myp1, myp2);
     cout<<"线长为:"<<line.getLen();
     return 0;
    }

    总结:定义了点这个类和线这个类。

      point类,数据——点的坐标。

          行为——为line类提供坐标

      line类,数据——两个piont的点。

          行为——计算两个点的距离并显示

    总之,该例子,将类作为作为一种数据来使用。

  • 相关阅读:
    VMware安装Centos7超详细过程
    Linux部署Web项目
    Entity Framework快速入门IQueryable与IEnumberable的区别
    ASP.NET MVC3中的路由系统(Routes)
    C# Lambda表达式概述
    WCF大数据量传输解决要点
    div滚动条样式设计
    ASP.NET MVC 自定义路由
    C# Lambda表达式学习笔记
    C# 操作excel
  • 原文地址:https://www.cnblogs.com/damaoranran/p/8453634.html
Copyright © 2011-2022 走看看