zoukankan      html  css  js  c++  java
  • 【C++基础】类的组合

    所谓类的组合是指:类中的成员数据是还有一个类的对象或者是还有一个类的指针或引用。通过类的组合能够在已有的抽象的基础上实现更复杂的抽象。 比如:

    1、按值组合

    #include<iostream.h>
    #include<math.h>
    class Point
    {
    public:
    	Point(int xx,int yy)//构造函数
    	{
    		x=xx;
    		y=yy;
    		cout<<"Point's constructor was called"<<endl;
    	}
    	Point(Point &p);//拷贝构造函数
    	int GetX(){return x;
    	int GetY(){return y;}
    	~Point()
    	{
    		cout<<"Point's destructor was called"<<endl;
    	}
    private:
    	int x,y;
    	};
    	Point::Point(Point &p)
    	{
    		x=p.x;
    		y=p.y;
    		cout<<"Point's copyConstructor was called"<<endl;
    	}
    	class Distance
    	{
    	private:
    		Point p1,p2;  //按值组合,将类Point的对象声明为类Distance的数据成员
    		double dist;
    	public:
    		Distance(Point a,Point b);//包括Point类
    		double GetDis(void)
    		{
    			return dist;
    		} 
    		~Distance()
    		{
    			cout<<"Distance's destructor was called"<<endl;
    		}
    	};
    	Distance::Distance(Point a,Point b):p1(a),p2(b)
    	{
    		double x=double(p1.GetX()-p2.GetX());
    		double y=double(p1.GetY()-p2.GetY());
    		dist=sqrt(x*x+y*y); 
    		cout<<"Distance's constructor was called"<<endl<<endl;
    	}
    	void main()
    	{
    		Point myp1(1,1),myp2(4,5);
    		Distance myd(myp1,myp2);
    		cout<<'
    '<<"the distance is: "<<myd.GetDis()<<endl<<endl;
    	}
    2、按引用组合

    class ZooAnimal
    {
    public:
    	// ....
    private:
    	Endangered *_endangered1 ; //按指针组合
    	Endangered &_endangered2 ; //按引用组合
    };

    另外再看一个样例:

        假设鸟是能够飞的,那么鸵鸟是鸟么?鸵鸟怎样继承鸟类?[美国某著名分析软件公司2005年面试题]
    解析:假设全部鸟都能飞,那鸵鸟就不是鸟!回答这样的问题时,不要相信自己的直觉!将直觉和合适的继承联系起来还须要一段时间。
        依据题干能够得知:鸟是能够飞的。也就是说,当鸟飞行时,它的高度是大于0的。鸵鸟是鸟类(生物学上)的一种。但它的飞行高度为0(鸵鸟不能飞)。
        不要把可替代性和子集相混淆。即使鸵鸟集是鸟集的一个子集(每一个驼鸟集都在鸟集内),但并不意味着鸵鸟的行为可以取代鸟的行为。可替代性与行为有关,与子集没有关系。当评价一个潜在的继承关系时,重要的因素是可替代的行为,而不是子集。
          答案:假设一定要让鸵鸟来继承鸟类,能够採取组合的办法,把鸟类中的能够被鸵鸟继承的函数挑选出来,这样鸵鸟就不是“a kind of”鸟了,而是“has some kind of”鸟的属性而已。代码例如以下:

    #include<string>
    #include<iostream>
    using namespace std;
    class bird
    {
    public:
    	void eat()
    	{
    		cout<<"bird is eating"<<endl;
    	}
    	void sleep()
    	{
    		cout<<"bird is sleeping"<<endl;
    	}
    	void fly();
    };
    
    class ostrich
    {
    public:
    	eat()
    	{
    		smallBird.eat();
    	}
    	sleep()
    	{
    		smallBird.sleep();
    	}
    private:
    	bird smallBird;  //在这里使用了组合,且是按值组合:将bird的一个对象声明为还有一类的数据成员
    };
    
    int main()
    {
    	ostrich xiaoq;
    	xiaoq.eat();
    	xiaoq.sleep();
    	return 0;
    }
    



  • 相关阅读:
    github使用及介绍
    git分支 & git标签
    nginx配置文件参考
    PHP优化
    Nginx优化
    Git安装及基础命令使用
    JavaScript框架设计-node节点
    论文爬取(一)
    JAVA日报
    JAVA日报
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4232317.html
Copyright © 2011-2022 走看看