对象成员指针实践

对象成员指针实例化时,先调用嵌套构造函数,在构造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;

}

转载于:https://www.cnblogs.com/bohat/p/7887563.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值