对象指针示例:
#include <iostream>
#include <stdlib.h>
#include "Coordinate.h"
using namespace std;
/*
对象指针
要求:
定义Coordinate类
数据成员:m_iX和m_iY;
声明对象指针,并通过指针控制对象
计算两个点、横纵坐标的和。
*/
class Coordinate {
public:
Coordinate();
~Coordinate();
public:
int m_iX;
int m_iY;
};
Coordinate::Coordinate()
{
cout << "Coordinate()" << endl;
}
Coordinate::~Coordinate()
{
cout << "~Coordinate()" << endl;
}
int main(void)
{
Coordinate *p1 = NULL;
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;
// Coordinate p1;
// Coordinate*p2=&p1;
// p2->m_iX = 100; // (*p).m_iX = 100;
// p2->m_iY = 200; // (*p).m_iY = 200;
// cout << p1.m_iX << "," << p1.m_iY << endl;
system("pause");
return 0;
}
打印结果(堆中):
主程序被注释区打印结果(栈中):