对象成员指针实践

对象成员指针实例化时,先调用嵌套构造函数,在构造line函数。 销毁对象时,先销毁嵌套构造函数coordinate,在销毁line函数,这个和嵌套对象成员函数不一样。

coordinate.h

#pragma once
class coordinate
{
public:
  coordinate(int x,int y);
  ~coordinate();
  int getX();
  int getY();
private:
  int m_ix;
  int m_iy;


};

 coordinate.cpp

#include "stdafx.h"
#include "coordinate.h"
#include <iostream>
using namespace std;

coordinate::coordinate(int x,int y)
{
  m_ix = x;
  m_iy = y;
}
coordinate::~coordinate()
{
  cout << "~coordinate()" << endl;
}
int coordinate::getX()
{
  return m_ix;
}
int coordinate::getY()
{
  return m_iy;
}

line.h

#pragma once
#include "stdafx.h"
#include <iostream>
using namespace std;
#include"coordinate.h"
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 "stdafx.h"
#include "line.h"
#include <iostream>
using namespace std;

line::line(int x1, int y1, int x2, int y2)
{
  m_pcoorA = new coordinate(x1, y1);
  m_pcoorB = new coordinate(x2, y2);


  cout << "line(int x1, int y1, int x2, int y2)" << endl;
}
line::~line()
{
  delete m_pcoorA;
  delete m_pcoorB;
  m_pcoorA = NULL;
  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;
}

main函数


#include "stdafx.h"
#include"coordinate.h"
#include <iostream>
#include "line.h"

using namespace std;

int main()
{
  line *p = new line(1, 2, 3, 4);
  p->printinfo();

  delete p;
  p = NULL;
  cout << sizeof(p) << endl;
  cout << sizeof(line) << endl;
  system("pause");
  return 0;

}

posted @ 2017-11-23 23:14  boht  阅读(139)  评论(0编辑  收藏  举报