这次呢我们写一个直角坐标系中的线段的代码,我们要描述这个线段呢,首先要有两个点
一个类是两个坐标点,另一个类是线段
下面以代码示例
#include <iostream>
using namespace std;
class Coordinate
{
public:
Coordinate()//无参构造函数
{
cout<<"Coordinate()"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
~Coordinate()
{
cout<<"~Coordinate()"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
void setX(int x)
{
m_iX=x;
}
int getX()
{
return m_iX;
}
void setY(int y)
{
m_iY=y;
}
int getY()
{
return m_iY;
}
private:
int m_iX;
int m_iY;
};
class Line
{
public:
Line()//无参构造函数
{
cout<<"Line"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
~Line()
{
cout<<"~Line"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
void setA(int x,int y)
{
m_coorA.setX(x);
m_coorA.setY(y);
}
void setB(int x,int y)
{
m_coorB.setX(x);
m_coorB.setY(y);
}
void printInfo(int x,int y)
{
cout<<"("<<m_coorA.getX()<<","<<m_coorA.getY()<<")"<<endl;
cout<<"("<<m_coorB.getX()<<","<<m_coorB.getY()<<")"<<endl;
}
private:
Coordinate m_coorA;//相当于实例化了一个Coordinate的类
Coordinate m_coorB;
};
int main()
{
Line *p=new Line();//实例化时实例化m_coorA,m_coorB,再实例化Line
delete p;//先销毁Line,再销毁m_coorB,m_coorA
system("pause");
return 0;
}
下面是代码运行的结果
我们可以看到Coordinate()被调用了两次,也就是实例化m_coorA,m_coorB的过程,然后是实例化Line,在这里我们没有其他操作,直接运行delete,我们从结果可以看到销毁的过程,先销毁了Line,然后销毁m_coorB,m_coorA,验证了我们的猜想,对应我们这个题目,创建一个线段时先创建A,B两个点,在把线连起来
我们实现一个线段的话,我们希望实例化的时候两个点A,B,就已经有了点并且能传入线段的类,下面我们把点传入并且验证一下A,B创建销毁的过程
#include <iostream>
using namespace std;
class Coordinate
{
public:
Coordinate(int x,int y)
{
m_iX=x;
m_iY=y;
cout<<"Coordinate()"<<"("<<m_iX<<","<<m_iY<<")"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
~Coordinate()
{
cout<<"~Coordinate()"<<"("<<m_iX<<","<<m_iY<<")"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
void setX(int x)
{
m_iX=x;
}
int getX()
{
return m_iX;
}
void setY(int y)
{
m_iY=y;
}
int getY()
{
return m_iY;
}
private:
int m_iX;
int m_iY;
};
class Line
{
public:
Line(int x1,int y1,int x2,int y2):m_coorA(x1,y1),m_coorB(x2,y2)
{
cout<<"Line"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
~Line()
{
cout<<"~Line"<<endl;//只是为了看构造函数的被调用的情况实际写代码这一行不用写
}
void setA(int x,int y)
{
m_coorA.setX(x);
m_coorA.setY(y);
}
void setB(int x,int y)
{
m_coorB.setX(x);
m_coorB.setY(y);
}
void printInfo()
{
cout<<"("<<m_coorA.getX()<<","<<m_coorA.getY()<<")"<<endl;
cout<<"("<<m_coorB.getX()<<","<<m_coorB.getY()<<")"<<endl;
}
private:
Coordinate m_coorA;//相当于实例化了一个Coordinate的类
Coordinate m_coorB;
};
int main()
{
Line *p=new Line(1,2,3,4);//实例化时先实例化m_coorA,再实例化m_coorB,再实例化Line
p->printInfo();
delete p;//先销毁Line,再销毁m_coorB,m_coorA
system("pause");
return 0;
}
我们传入的是A(1,2),B(3,4),从运行结果我们可以看出是先实例化A,再实例化B,销毁时先销毁B,再销毁A,打印也是正常进行的
现在我们讨论一下两个类构造函数的初始化列表的问题
如果坐标类是默认构造函数(无参构造函数),那么在线的类中可以不使用初始化列表,如果坐标类的使用的是有参构造函数,那线中的类必须使用初始化列表
关于这一点的理解请参考以下网址https://blog.csdn.net/hankai1024/article/details/7947989