美文网首页
继承和派生以及类的组合

继承和派生以及类的组合

作者: 夕阳下的不回头 | 来源:发表于2018-09-06 11:13 被阅读7次

    继承和类的组合都是解决问题的好方法
    但是要视具体情况而定
    有些问题既能用继承也能用类的组合的时候
    我们首选组合 因为组合的语法相对简单
    (虽然我没用过0.0)
    组合就是直接在一个类的定义里还有另外一个类
    比如
    Class A
    {
    };
    Class B
    {
    A a;
    int c;
    }
    这个A不是基本数据类型 是个类 a是对象
    这种在一个类中还有另外一个类的情况就是类的组合
    例子:转自鸡啄米
    Distance类就是组合类,可以计算两个点的距离,它包含了Point类的两个对象p1和p2。

       #include <iostream>
       using namespace std;
    
       class Point
       { 
       public:
                 Point(int xx,int yy)   { X=xx; Y=yy; } //构造函数
                 Point(Point &p);
                 int GetX(void)     { return X; }        //取X坐标
                 int GetY(void)     { return Y; } //取Y坐标
       private:
                 int X,Y; //点的坐标
       };
    
       Point::Point(Point &p)
       {
                 X = p.X;
                 Y = p.Y;
                 cout << "Point拷贝构造函数被调用" << endl;
       }
    
       class Distance
       {
       public:
                Distance(Point a,Point b); //构造函数
                double GetDis()   { return dist; }
       private:
                Point  p1,p2;
                double dist;               // 距离
        };
        // 组合类的构造函数
        Distance::Distance(Point a, Point b):p1(a),p2(b)
        {
                cout << "Distance构造函数被调用" << endl;
                double x = double(p1.GetX() - p2.GetX());
                double y = double(p1.GetY() - p2.GetY());
                dist = sqrt(x*x + y*y);
                return;
        }
    
        int _tmain(int argc, _TCHAR* argv[])
        {
               Point myp1(1,1), myp2(4,5);
               Distance myd(myp1, myp2);
               cout << "The distance is:";
               cout << myd.GetDis() << endl;
               return 0;
        }
    

    C++类体系中,不能被派生类继承的有_________。

    A 析构函数
    B 虚函数
    C 静态成员函数
    D 静态成员函数
    选A 为毛呢。。。可能是因为派生类的成员和以前的不一样了 没法直接拿过来析构

    相关文章

      网友评论

          本文标题:继承和派生以及类的组合

          本文链接:https://www.haomeiwen.com/subject/yritgftx.html