//Coordinate.h
/**
定义一个坐标类
*/
class Coordinate
{
public:
Coordinate(int x,int y);//构造函数
~Coordinate();
void setX(int x);
int getX();
void setY(int y);
int getY();
private:
int m_iX;
int m_iY;
};
//Coordinate.cpp
#include <iostream>
#include "Coordinate.h"
using namespace std;
//调用构造函数
Coordinate::Coordinate(int x ,int y)
{
m_iX = x;
m_iY = y;
cout << "Coordinate()"<<m_iX<<","<<m_iY<<endl;
}
Coordinate::~Coordinate()
{
cout << "~Coordinate "<<m_iX<<","<<m_iY<<endl;
}
void Coordinate::setX(int x)
{
m_iX = x;
}
int Coordinate::getX()
{
return m_iX;
}
void Coordinate::setY(int y)
{
m_iY = y;
}
int Coordinate::getY()
{
return m_iY;
}
//line.h
/**
定义一个线段类
*/
#include "Coordinate.cpp"
class Line
{
public:
Line(int x1,int y1,int x2,int y2);
~Line();
void setA(int x,int y);
void setB(int x, int y);
void printInfo();
private:
Coordinate m_coorA;//对象数据成员
Coordinate m_coorB;
};
//line.cpp
#include <iostream>
#include "Line.h"
using namespace std;
Line::Line(int x1,int y1,int x2,int y2):m_coorA(x1,y1),m_coorB(x2,y2)
{
cout << "Line()"<< endl;
}
Line::~Line()
{
cout << "~Line()"<<endl;
}
void Line::setA(int x,int y)
{
m_coorA.setX(x);
m_coorB.setY(y);
}
void Line::setB(int x,int y)
{
m_coorB.setX(x);
m_coorB.setY(y);
}
void Line::printInfo()
{
cout << "("<<m_coorA.getX()<<","<<m_coorA.getY()<<")"<<endl;
cout << "("<<m_coorB.getX()<<","<<m_coorB.getY()<<")"<<endl;
}
//demo.cpp
#include <iostream>
#include "Line.cpp"
using namespace std;
int main()
{
Line *p = new Line(1,2,3,4);
//p->printInfo();
delete p;
p = NULL;
return 0;
}
从运行结果来看,先连续调用了两次坐标类的构造函数,再调用了一次线段类的构造函数,这就意味着先创建了两个坐标类的对象,这两个坐标类的对象就是A点和B点,然后才调用线段这个对象,线段这个对象是在A点和B点初始化完成之后才被创建。而在销毁时,先调用的是线段类的西沟函数,然后连续调用两次坐标类的析构函数。可见,对象成员的创建与销毁的过程正好相反,也验证了我们之前给出的结论。
在实例化对象时,先实例化点A,再实例化点B,最后实例化线段;在销毁对象时,先销毁线段,再销毁点B,最后销毁点A。