C++类的组合

一、组合的概念

1、类中的成员是另一个类的对象。

2、可以在已有抽象的基础上实现更复杂的抽象。

二、类组合的构造函数设计

1、原则

不仅要负责对本类中的基本类型成员数据初始化,也要对对象成员初始化。

2、声明形式

类名::类名(对象成员形参,本类成员形参):对象1(参数),对象2(参数),……

{

        //函数体其他语句

}

#include "stdafx.h"
#include 
#include 
#include 
#include 


using namespace std;
//Point
class Point
{
private:
	double x,y;
public:
	Point(double x,double y):x(x),y(y)
	{
	}
	Point(const Point &p)//Copy constructor 
	{
		x=p.x;
		y=p.y;
	}
	double getX()
	{
		return x;
	}
	double getY()
	{
		return y;
	}
};
//Line
class Line
{
private:
	double length;
	Point a,b;
public:
	Line(Point a,Point b):a(a),b(b)
	{
		double x=a.getX()-b.getX();
		double y=a.getY()-b.getY();
		length=sqrt(x*x+y*y);
	}
	double getLength()//get the length of line
	{
		return length;
	}
	Point getA()//get a point
	{
		return a;
	}
	Point getB()//get b point
	{
		return b;
	}

};
int _tmain(int argc, _TCHAR* argv[])
{
	Point a(1,2),b(3,4);
	Line ab(a,b);
	double i=ab.getB().getX();
	cout<

 

你可能感兴趣的:(C++,从零开始学习C++)