对象成员:
一个对象中包含其他对象
如:
class Line{
public:
Line();
private:
Coordinate m_coorA;
Coordinate m_coorB;
}
当实例化这样一个对象时,会先实例化m_coorA,再实例化m_coorB,最后实例化Line
对象消亡时,会先销毁Line,再m_coorB,最后m_coorA
如果坐标类有一个默认构造函数,那么在实例化线段对象的时候,不使用初始化列表。
如果坐标类要求必须有参数传入,那么在实例化线段类的时候,必须用初始化列表讲相应的值传递给坐标类
Coordinate.h
class Coornidate
{
public:
Coornidate(int x,int y);
~Coornidate();
void setX(int x);
int getX();
void setY(int y);
int getY();
private:
int m_iX;
int m_iY;
};
Coornidate.cpp
#include<iostream>
#include"coordinate.h"
using namespace std;
Coornidate::Coornidate(int x,int y)
{
m_iX=x;
m_iY=y;
cout<<"Coornidate() "<<"("<<m_iX<<","<<m_iY<<")"<<endl;
}
Coornidate::~Coornidate()
{
cout<<"~Coornidate() "<<"("<<m_iX<<","<<m_iY<<")"<<endl;
}
void Coornidate::setX(int x)
{
m_iX=x;
}
int Coornidate::getX()
{
return m_iX;
}
void Coornidate::setY(int y)
{
m_iY=y;
}
int Coornidate::getY()
{
return m_iY;
}
Line.h
#include"Coordinate.h"
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:
Coornidate m_coorA;
Coornidate 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_coorA.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;
/**
* 对象成员
要求:
定义两个类:
坐标类:Coordinate
数据成员:横坐标m_iX,纵坐标m_iY
成员函数:构造函数,析构函数,数据封装函数
线段类:Line
数据成员:点A m_coorA,点B m_coorB
成员函数:构造函数,析构函数,数据封装函数,信息打印函数
*/
int main()
{
Line *p=new Line(1,2,3,4);
p->printInfo();
delete p;
p=NULL;
return 0;
}
Coornidate() (1,2)
Coornidate() (3,4)
Line()
(1,2)
(3,4)
~Line()
~Coornidate() (3,4)
~Coornidate() (1,2)