对象指针
//Coordinate.h
class Coordinate
{
public:
Coordinate();
~Coordinate();
public:
int m_iX;
int m_iY;
};
//Coordinate.cpp
#include "Coordinate.h"
#include <iostream>
using namespace std;
Coordinate::Coordinate()
{
cout << "Coordinate()" << endl;
}
Coordinate::~Coordinate()
{
cout << "~Coordinate" << endl;
}
//demo.cpp
#include "Coordinate.cpp"
#include <iostream>
#include <stdlib.h>
int main()
{
/* 使用两种方法定义对象指针(堆中) */
// Coordinate *p1 = NULL;//定义一个对象指针
// //让p1指向一段内存,这里也可以写成p1 = new Coordinate(),因为其默认构造函数没有参数
// p1 = new Coordinate;
// Coordinate *p2 = new Coordinate();
// /* 使用两种方法让对象指针访问数据成员 */
// p1 -> m_iX = 10;
// p1 ->m_iY = 20;
// (*p2).m_iX = 30;
// (*p2).m_iY = 40;
// cout << p1 ->m_iX + (*p2).m_iX << endl;//横坐标相加
// cout << p1 ->m_iY + (*p2).m_iY << endl;//纵坐标相加
// delete p1;
// p1 = NULL;
// delete p2;
// p2 = NULL;
//===============================
//从栈中实例化一个对象p1
Coordinate p1;
Coordinate *p2 = &p1;//让对象指针p2指向p1
p2 -> m_iX = 10;
p2 -> m_iY = 20;
//这里我们来打印p1的横坐标和纵坐标,来说明是对象指针p2操纵了对象p1
cout << "the Coordinate of obj p1 is :("<<p1.m_iX<<","<<p1.m_iY<<endl;
return 0;
}
对象成员指针
对象的指针成为一个类的数据成员叫做对象成员指针,与对象成员之间区别。
//Coordinate.h
class Coordinate
{
public:
Coordinate(int x ,int y);
~Coordinate();
int getX();
int getY();
public:
int m_iX;
int m_iY;
};
//Coordinate.cpp
#include "Coordinate.h"
#include <iostream>
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;
}
int Coordinate::getX()
{
return m_iX;
}
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 printInfo();
private:
Coordinate *m_pCoorA;//对象成员指针
Coordinate *m_pCoorB;
};
//Line.cpp
#include "Line.h"
#include <iostream>
using namespace std;
Line::Line(int x1,int y1,int x2,int y2)
{
//从堆中实例化两个坐标对象,并使指针m_pCoorA和m_pCoorB分别指向这两个对象
m_pCoorA = new Coordinate(x1,y1);
m_pCoorB = new Coordinate(x2,y2);
cout << "Line()" << endl;
}
Line::~Line()
{
delete m_pCoorA;
m_pCoorA = NULL;
delete m_pCoorB;
m_pCoorB = NULL;
cout<< "~Line()"<< endl;
}
void Line::printInfo()
{
cout << "printInfo()" << endl;
cout << "(" << m_pCoorA->getX() << ","<<m_pCoorA->getY()<<")"<<endl;
cout << "(" << m_pCoorB->getX() << ","<<m_pCoorB->getY()<<")"<<endl;
}
//demo.cpp
#include "Line.cpp"
#include <iostream>
#include <stdlib.h>
int main()
{
//从堆中实例化一个线段对象,并传入四个参数
Line *p = new Line(1,2,3,4);
delete p;
p = NULL;
cout << sizeof(p) << endl;
cout << sizeof(Line) << endl;
return 0;
}
从运行结果看,通过p是可以正常调用信息打印printInfo()函数的(屏幕中间已经打印出信息打印函数名,并且也打印出了A点坐标和B点坐标)。最后,打印出4和8,告诉我们,指针p本身大小为4,而Line对象大小为8(说明Line仅仅包含m_pCoorA和m_pCoorB这两个对象成员指针)。